Spread the love

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

#include <stdio.h>

unsigned char swapNibbles(unsigned char x)
{
    return ( (x & 0x0F)<<4 | (x & 0xF0)>>4 );
}

int main()
{
    unsigned char x = 0xAB;              //Assigned in single byte hexadecimal value
    printf("%x", swapNibbles(x));
    return 0;
}

 

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