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
- Swap bits in a given number
- How to swap two bits in a given integer?
- Check if bits of a number has count of consecutive set bits in increasing order
- Print numbers having first and last bits as the only set bits
- Toggle bits of a number except first and last 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
- How to swap two numbers without using a temporary variable?
- Swap three variables without using temporary variable
- First and Last Three Bits
- Unset the last m bits
- Sum of numbers with exactly 2 bits set
- Toggle the last m bits
- Set all odd bits of a number
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. 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