Swap two nibbles in a byte

About Nibble

A nibble is a four-bit representation whereas byte is eight-bit representation. There are two nibbles in a byte. For example AB(represented in hexadecimal) is be represented as 10101011 in a byte (or 8 bits). The two nibbles are (1010) and (1011). If we swap the two nibbles, we get 10111010 which is BA represented in hexadecimal.

To swap the nibbles, we can use bitwise ‘&’, bitwise ‘<<‘ and ‘>>’ operators. A byte can be represented using a unsigned char in C as size of char is 1 byte in a typical C compiler. Following is C program to swap the two nibbles in a byte.

Swap two nibbles in a byte

 

Suggested Reading

  1. Find position of the only set bit
  2. Write a Macro’s Set,clear and toggle n’th bit using bit wise operators?
  3. Count number of 1s in given binary number