3 ms·
x & (1<<n) is not the same as (x % pow(2, n)) Take x = 2 and n = 1 x & (1 << n) = 0b10 & 0b10 = 0b10 x % pow(2, n) = 2 % 2 = 0 = 0b0 0b0 /= 0b10 fwiw,
by alexgartrell 16y ago
x & (1<<n) is not the same as (x % pow(2, n))
Take x = 2 and n = 1
x & (1 << n) = 0b10 & 0b10 = 0b10
x % pow(2, n) = 2 % 2 = 0 = 0b0
0b0 /= 0b10
fwiw, you were actually looking for (x & ((1 << n) - 1)) = (x % pow(2, n))
That aside, you're absolutely right. Using bit ops is almost always a bad idea. It turns a simple store (to a byte-addressed memory address) into a read, manipulate, and store (to a bit within a byte-addressed memory address) which can have pretty bad side affects in any concurrent environment.