C++ program to swap two nibbles in a byte

Each byte has 8 bits. Each nibble has 4 bits i.e, half the number of bits in a byte. The problem given above is to swap the two nibbles in a byte. For example, 16 in binary representation is 00010000. Hence, it has two nibbles 0001 and 0000. Swapping these nibbles we get 00000001 which is the binary representation of 1. Therefore, the output is 1.

We can swap the nibbles using “&”, “<<” and “>>” operators. The code to swap the nibbles is as given below:

#include <bits/stdc++.h> 
using namespace std; 
int swapNibbles(int x) 
    return ( (x & 0x0F) << 4 | (x & 0xF0) >> 4 ); 
// Driver code 
int main() 
    int x = 16; 
    cout << swapNibbles(x); 
    return 0; 

“x & 0x0F” represents the last four digits of the binary number. Here the last four digits of “00010000” are “00000000 “.”<<” shifts the last four digits to the left and makes the current last four digits to zero i.e, “00000000” in this case.

“x & 0xF0” represents the first four digits of the binary number. Here the first four digits of “00010000” are “00010000”. “>>” shifts the first four digits to the right and makes the current first four digits to zero i.e, “00000001”.

The “|” operator combines the two nibbles together to form a new binary number.

If we run our program, we will see the output given:



...Program finished with exit code 0                                                                                                 

Press ENTER to exit console.                                                                                                         

Leave a Reply

Your email address will not be published. Required fields are marked *