BitMask Index of LSB doubt

To get index of the least significant bit how is this is used?

log2(N& -N) +1

How is this working? How are we using negative numbers here? And how do we represent them at binary level to use it in this manner ?

hello @bishal_c
log2(N&(-N)) +1 will give u position of first set bit (counting from right and 1 based indexing .
if n is a positive number , so -n will be a negative number and negative number are represented in 2’s compliment ,which is ~n+1 , ~n has all the bits of n inverted due to which we get 0 in place of 1 and vice versa so when we add 1 to ~n then that 1 occupies the first rightmost 0 in (~n)(which is same as rightmost 1 value in n) and other bits have inverted values or zero values . so when we perform & operation we get only rightmost bit set in the function ,and then we perform logn (base2) to get corresponding index.

eg :- n = 1110010100
~n= 0001101011
~n+1=-n= 0001101100
(n&(-n))= 0000000100 = 4
log(4) =2
2+1=3 which is the answer

but won’t -n which when represented in that manner signify another positive decimal value? So in that case won’t the meaning change ? Like if I have a negative number and I represent it as 001100XXX … and that same binary number would be some natural number right…?

we will never have same representation for two different numbers, please read about 2’s complement, signed ,unsigned number for clarity.

Oh…ok…thank you :slight_smile: