Binlogs
27 subscribers
18 photos
125 links
Download Telegram
n & -n

will tell you the position of the least significant bit (lsb) of a number. eg: 4 -> 4 & -4 = 4 and 7 -> 7 & -7 = 1.
on the lsb (the first one from the right) is found on 2^2 place, on the second case 2^0.

this also tells you, how many times a number can be divided by two before becoming not divisible. for 4 it is 2 and for 7 it is 0.

why does this work?
since negative numbers are expressed using two's complement, (if a number has zeros to the right all of them are gonna be flipped then we add 1 to it, which will make the ones to zero until reaches the lsb). and the 'AND' operation will make it so that only this parts are the same while all the other bits are zero.


eg: 4 represented in 8 bits.
00000100
then -4 will be (11111011 + 1) = (11111100)
00000100
&
11111100
——————
00000100
which is 4.

n & (n-1)

will change the lsb to zero. eg: 4 -> 4 & 3 = 0 since 4 is 100 in binary. 7 -> 7 & 6 = 111 & 110 = 110. thus 111 is changed to 110.

since power of 2 always have only one set bit when described in binary, performing this will always result in 0.

credit: https://trap.jp/post/2674/

#lessons
🔥1