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
unsigned char swapNibbles(unsigned char x)
return ( (x & 0x0F)<<4 | (x & 0xF0)>>4 );
unsigned char x = 0xAB; //Assigned in single byte hexadecimal value
- Find position of the only set bit
- Write a Macro’s Set,clear and toggle n’th bit using bit wise operators?
- Count number of 1s in given binary number