C++ Program: How to Swap Bits in Odd & Even Positions for Unsigned int

0
1171

Here is the program to swap bit in odd and even positions of 32-bit unsigned integer.

For Even- To do this we can AND with bitmask 0xAAAAAAAAAA. The number 0xAAAAAAAA which is a 32 bit number with even bits set (0xA is decimal 10, 1010 binary).

For Odd – For selecting all the odd bits we can AND with bitmask 0×55555555, which is a number with all odd bits sets (0x5 is decimal5, 0101 in binary)

Every even position bit is swapped with adjacent bit on right side (even position bits are highlighted in binary representation of 23), and every odd position bit is swapped with adjacent on left side we actually need to shift left (respectively right) of one position and OR the two results.

 

LEAVE A REPLY

Please enter your comment!
Please enter your name here