0

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

del bao
  • 1,084
  • 1
  • 11
  • 20
  • Not bit manipulation, but you could do `x >= 0 ? (x - x % 2) : (x + x % 2)`. If x is unsigned, then you can just do `x - x % 2`. – Scovetta Feb 15 '17 at 05:57
  • bitwise or with one: `x = x | 1` ... sorry, see my answer, i thought you want to just set the rightmost bit to one. – Selçuk Cihan Feb 15 '17 at 06:00

5 Answers5

6

Just do the opposite (well, not exactly but you get what I mean): n | (n+1)

zwer
  • 24,943
  • 3
  • 48
  • 66
1

To set the last zero bit to one, you can add one to it and then bitwise or with itself

(x + 1) | x

Selçuk Cihan
  • 1,979
  • 2
  • 17
  • 30
0

For setting a kth 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

rink.attendant.6
  • 44,500
  • 61
  • 101
  • 156
  • @vivek-pratap-chaurasia : Your answer refers to "setting a specific bit of x to 1". But the question is "setting the **last zero bit** to 1", without first finding which bit to set. Therefore, "101" (5) should become "111" (7) after the operation. – Siu Ching Pong -Asuka Kenji- Aug 12 '17 at 14:02
0

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).

Cyrusmith
  • 747
  • 1
  • 9
  • 17
-1

To set the last (lowest) 0 bit to 1:

x|1
fei_hsueh
  • 161
  • 1
  • 11
  • @fei-hsueh: Your answer refers to "setting the last bit of x to 1". But the question is "setting the **last zero bit** to 1". Therefore, "101" (5) should become "111" (7) after the operation. – Siu Ching Pong -Asuka Kenji- Aug 12 '17 at 14:00