Swap every two bits in bytes
Swap all the pair of bits in a byte. Before swapping: 11-10-11-01 After swapping: 11-01-11-10
Input : 00000010 Output : 00000001 Input : 00000100 Output : 00001000
x = ((x & 0x55555555) >> 1) | ((x & 0xAAAAAAAA) <> 1 extracts the high bit position and shifts it to the low bit position.
Similarly the expression (x & 0xAAAAAAAA) << 1 extracts the low bit from each pair and shifts it to the high bit position.
The two parts are then combined using bitwise-OR.
x= 00011010 ((x & 0xAAAAAAAA) >> 1) = 00001010 >> 1 = 00000101 ((x & 0x55555555) << 1) = 00010000 <> 1) | ((x & 0x55555555) << 1) = 00100101
Below is the implementation of the above idea:
Time Complexity: O(1)
Space Complexity: O(1)
This article is contributed by Saumya and improved by Kasina Dheeraj .If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.