How would I change the least significant bit to 0 without affecting the rest of the value, for example:
0xffffffff , for example in C or Python? I am not a mathematical genius, so for me it's a hassle to find out how to achieve this.
n = 0 // clear this bit 0xffffffff &= ~(1U << n) = 0xfffffffe
Try this to clear the least significant bit:
int x = 0xffffffff; ... /* clear least significant bit */ x &= ~1;
To set the LSB
int x = 0xffffffff; ... /* set least significant bit */ x |= 1;
To change the LSB
int x = 0xffffffff; ... /* change least significant bit */ x ^= 1;
If you want to extent that to set / clear / change bit
n, change the
unsigned x = (x>>1U) x = (x<<1U)
This is easy to understand ....
Let x = 10010101011
step 1 : x = 0 1001010101 // x>>1
step 2 : x = 1001010101 0 // x<<1
Another method can be unsigned x =
x & 0Xfffffffe which is equal to
11111111111111111111111111111110 i.e 31 bits 1 to keep bit 31 to 1 as it occours in x .
Hope this helps !
~0 evaluates to all bits set to
1. Assign this to an
unsigned int variable and shift it left by 1 bit so that all bits are
1 except the least significant bit. The use bitwise
x to toggle the least significant bit.
unsigned int x = 0xffffffff; unsigned int y = 0; x = x & (~0 << 1);
User contributions licensed under CC BY-SA 3.0