1. Swap 2 nibble
2. Swap all even and odd bits
3. Swapping pair of bits in a Byte
1. Swap 2 nibble
(num & 0x0F)<<4 | (num & 0xF0)>>4 )
we use the above code to shift 2 nibble.
The working of the code is explained below:
Consider the number 12345678
(x & 0x0F)<<4 gives 56780000
(x & 0xF0)>>4 gives 00001234
so the final answer after using the OR operator is 56781234.
2. Swap all even and odd bits
Below are the steps to get the result:
1. Get all the even bits
2. Get all the odd bits
3. Right shift all the even bits by 1
4. Left shift all the odd bits by 1
To get the even bits, we do a bitwise AND with the number and 0xAAAAAAAA. “0xAAAAAAAA” is 32 bit number with all the even bits set to 1 and odd bits set to 0.
To get the even bits, we do a bitwise AND with the number and 0x55555555
. “0x55555555” is 32 bit number with all the odd bits set to 1 and odd bits set to 0.
3. Swapping pair of bits in a Byte
Before swapping: 11-10-11-01 After swapping: 11-01-11-10
x = ((x & 0b10101010) >> 1) | ((x & 0b01010101) << 1)
• The expression x & 0b10101010 extracts the high bit from each pair, and then >> 1 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.
Solution in C++
#include<iostream> #include<vector> #include<string> using namespace std; void swap_nibble(unsigned char num) { char temp = num; cout<<"The number "<<temp <<" after nibble swap = "<<((num & 0x0F)<<4 | (num & 0xF0)>>4)<<endl; } void swap_even_odd(unsigned int num) { int temp = num; unsigned int even_bits = num & 0xAAAAAAAA; unsigned int odd_bits = num & 0x55555555; even_bits >>= 1; // Right shift even bits odd_bits <<= 1; // Left shift odd bits cout<<"The number "<<temp <<" after swapping even and odd bit is = "<<(even_bits | odd_bits)<<endl; } void swap_pair(unsigned int num) { int temp = num; cout<<"The number "<<temp <<" after pairwise swap is = "<<( ((num & 0b10101010) >> 1) | ((num & 0b01010101) << 1))<<endl; } int main() { unsigned char str = 100; swap_nibble(str); unsigned int num = 23; // 00010111 swap_even_odd(num); unsigned int num_1 = 4; swap_even_odd(num_1); }