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.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- How to swap two bits in a given integer?
- Check if all bits can be made same by flipping two consecutive bits
- Swap bits in a given number
- Swap all odd and even bits
- 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
- For every set bit of a number toggle bits of other
- Minimum bit flips such that every K consecutive bits contain at least one set bit
- Minimum flips required to form given binary string where every flip changes all bits to its right as well
- 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?
- Print first n numbers with exactly two set bits
- Alternate bits of two numbers to create a new number
- Check if bits in range L to R of two numbers are complement of each other or not
- Number of mismatching bits in the binary representation of two integers
- Maximum Sum of Products of two arrays by toggling adjacent bits
- Count of even set bits between XOR of two arrays
- Program to find the Nth natural number with exactly two bits set
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