A nibble is a four-bit aggregation, or half an octet. There are two nibbles in a byte.
Given a byte, swap the two nibbles in it. For example 100 is be represented as 01100100 in a byte (or 8 bits). The two nibbles are (0110) and (0100). If we swap the two nibbles, we get 01000110 which is 70 in decimal.
We strongly recommend that you click here and practice it, before moving on to the solution.
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.

[pastacode lang=”c” manual=”%23include%20%3Cstdio.h%3E%0A%20%0Aunsigned%20char%20swapNibbles(unsigned%20char%20x)%0A%7B%0A%20%20%20%20return%20(%20(x%20%26%200x0F)%3C%3C4%20%7C%20(x%20%26%200xF0)%3E%3E4%20)%3B%0A%7D%0A%20%0Aint%20main()%0A%7B%0A%20%20%20%20unsigned%20char%20x%20%3D%20100%3B%0A%20%20%20%20printf(%22%25u%22%2C%20swapNibbles(x))%3B%0A%20%20%20%20return%200%3B%0A%7D” message=”C programming” highlight=”” provider=”manual”/]

Output:

70

Explanation:
100 is 01100100 in binary. The operation can be split mainly in two parts
1) The expression “x & 0x0F” gives us last 4 bits of x. For x = 100, the result is 00000100. Using bitwise ‘<<‘ operator, we shift the last four bits to the left 4 times and make the new last four bits as 0. The result after shift is 01000000. 2) The expression “x & 0xF0” gives us first four bits of x. For x = 100, the result is 01100000. Using bitwise ‘>>’ operator, we shift the digit to the right 4 times and make the first four bits as 0. The result after shift is 00000110.

At the end we use the bitwise OR ‘|’ operation of the two expressions explained above. The OR operator places first nibble to the end and last nibble to first. For x = 100, the value of (01000000) OR (00000110) gives the result 01000110 which is equal to 70 in decimal.

[ad type=”banner”]