Check if adjacent bits are set in binary representation of a given number

Given a number, check if adjacent bits are set in binary representation of it.

 

Naive Solution would be to consider every bit present in the number one by one and compare it with its previous bit. If the current bit is same as previous bit, then we have found a pair whose adjacent bits are 1.
 

The expression (n & (n << 1) or (n & (n >> 1) will return true if n contains any pair whose adjacent bits are 1. For example,

 

00101101   &                 (n)
01011010                     left shift n by 1
~~~~~~~~
00001000                     (n & (n << 1))  

C++

Download   Run Code

Output:

67 in binary is 01000011
Adjacent pair of set bits found

 
Read More –

Bit Hacks – Part 1 (Basic)
Bit Hacks – Part 2 (Playing with k’th bit)
Bit Hacks – Part 3 (Playing with rightmost set bit of a number)
Bit Hacks – Part 4 (Playing with letters of English alphabet)
Bit Hacks – Part 5 (Find absolute value of an integer without branching)

 
Suggested Read: https://graphics.stanford.edu/~seander/bithacks.html
 

Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz