Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get position of right most set bit in C

int a = 12;

for eg: binary of 12 is 1100 so answer should be 3 as 3rd bit from right is set.

I want the position of the last most set bit of a. Can anyone tell me how can I do so.

NOTE : I want position only, here I don't want to set or reset the bit. So it is not duplicate of any question on stackoverflow.

like image 735
ram singh Avatar asked Jul 13 '15 20:07

ram singh


People also ask

How do you find the position of the most significant bit?

Given a number, find the greatest number less than the given a number which is the power of two or find the most significant bit number .

How do I know if my bit is rightmost?

RIghtmost set bit can be easily found using 2's complement i.e. via (N & ~ (N - 1)) or using the XOR operator where “N” is the given number. Leftmost set bit can be easily found by simply right shifting the given number “N” till that number is > 0.

Which bit position is the most significant bit?

In a binary number, the bit furthest to the left is called the most significant bit (msb) and the bit furthest to the right is called the least significant bit (lsb). The MSB gives the sign of the number (sign bit) , 0 for positive and 1 for negative. The remaining bits hold the magnitude of the number.


1 Answers

This answer Unset the rightmost set bit tells both how to get and unset rightmost set bit for an unsigned integer or signed integer represented as two's complement.

get rightmost set bit,

x & -x
// or
x & (~x + 1)

unset rightmost set bit,

x &= x - 1
// or
x -= x & -x  // rhs is rightmost set bit

why it works

x:                     leading bits  1  all 0
~x:           reversed leading bits  0  all 1
~x + 1 or -x: reversed leading bits  1  all 0
x & -x:                       all 0  1  all 0

eg, let x = 112, and choose 8-bit for simplicity, though the idea is same for all size of integer.

// example for get rightmost set bit
x:             01110000
~x:            10001111
-x or ~x + 1:  10010000
x & -x:        00010000

// example for unset rightmost set bit
x:             01110000
x-1:           01101111
x & (x-1):     01100000
like image 110
qeatzy Avatar answered Oct 21 '22 07:10

qeatzy