by jihadjihad · 4y ago · 0 comments
Last year I was in an interview and something around writing a program to find out if an integer is a power of 2 came up. I remembered the example from the doc above and used that (you basically AND your integer with itself minus one, which makes sense because any power of 2 is going to be 1 followed by some zeroes...see below). I got the job!
10000
& 1111
______
1DUP DUP NEG AND =
> & 1111
> ______
> 1
Wouldn't this result in 0 and not 1?
You would use `bool( nn and not (nn&(nn-1)) )`
Let's try for 15
start 0b1111
sans1 0b1110
anded 0b1110
not 0b0000
Now 8 start 0b1000
sans1 0b0111
anded 0b0000
not 0b0001
It's basically a claim that, in binary, only powers of two won't have any overlapping bits between the initial number and that number minus one.Doesn't work for 0 so you have to special case it.
AND'ing each bit of the two numbers yields only 0 bits:
10000
&01111
______
00000