how to check if number is power of 8 or not using bitwise operators?
Bitwise operators
Hey Aastha, there are two conditions a number n will fulfil if it is power of 8 which are
- it is power of 2
- its only set bit is present at [0,3,6…] positions.
Now we can check if a number is power of 2 => (n & (n - 1)) will unset the rightmost set bit of a number. If the number is power of 2, it has only one bit set and (n & (n - 1)) will unset the only set bit. So we can say that (n & (n - 1)) returns 0 if n is power of 2 else it is not a power of 2.
Now, we have to check the positions of set bits, to check the position of its set bit we can use 0xB6DB6DB6 as a mask. The mask 0xB6DB6DB6 has 0 in all [0, 3, 6, 9 . . ] position. So if the expression !(n & 0xB6DB6DB6) is true, position of set bit in n is even.
The binary number for this hexadecimal number is (10110110110110110110110110110110).