we all know the trick n&(n-1) to set the last 1 bit to 0. e.g., 0110 & (0110-1) = 0100. but how about the reverse? set last 0 to 1? so 0110 becomes 0111?
I've done a great amount of search in stackoverflow and online. no result shows up
we all know the trick n&(n-1) to set the last 1 bit to 0. e.g., 0110 & (0110-1) = 0100. but how about the reverse? set last 0 to 1? so 0110 becomes 0111?
I've done a great amount of search in stackoverflow and online. no result shows up
To set the last zero bit to one, you can add one to it and then bitwise or with itself
(x + 1) | x
For setting a k
th bit of the number just do the following operation
n=n|(1<< k)
where k
is the bit you want to set.
I hope this helps.
For other bit manipulation, you can refer to this question: Manipulation of bits
For those who, like me, were looking for how to set lowermost zero bit, here's possible solution:
((((x-1) ^ x) & x) >>> 1) | x
For example, the lowermost zero bit of a number 101100
is the 3rd bit.
Let's break down the process of setting the lowermost bit:
Minus 1
and XOR to get the mask: (x-1) ^ x (101011
^ 101100
) = 000111
AND the mask with the number to get the position of the first non-zero bit: 000111
& 101100
= 000100
Shift right to the lowermost zero bit position: 000100
>>> 1 = 000010
OR to set the bit: 101100
| 000010
= 101110
UPD:
Alternative, and slightly more efficient solution is:
(x & -x) >>> 1 | x
,
where -x
is optimized version of ~(x-1)
.
To set the last (lowest) 0 bit to 1:
x|1