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 & 0b10101010) >> 1) | ((x & 0b01010101) <> 1 extracts the high bit position and shifts it to the low bit position.
Similarly the expression (x & 0b01010101) << 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 & 0b10101010) >> 1) = 00001010 >> 1 = 00000101 ((x & 0b01010101) << 1) = 00010000 <> 1) | ((x & 0b01010101) << 1) = 00100101
Below is the implementation of the above:
Note: This solution works for only 8 bit.
- Swap all odd and even bits
- How to swap two bits in a given integer?
- Swap bits in a given number
- Check if bits of a number has count of consecutive set bits in increasing order
- Toggle bits of a number except first and last bits
- Print numbers having first and last bits as the only set bits
- Swap two nibbles in a byte
- Number of ways to swap two bit of s1 so that bitwise OR of s1 and s2 changes
- Swap three variables without using temporary variable
- Bit manipulation | Swap Endianness of a number
- How to swap two numbers without using a temporary variable?
- First and Last Three Bits
- Same Number Of Set Bits As N
- Set all even bits of a number
- Toggle the last m bits
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 Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : Mithun Kumar