In this blog post, we learn how to write a C Program to swap two nibbles in a byte?. We will write the C program to swap two nibbles in a byte using the Bitwise Operators. We will also create a function to swap two nibbles in a byte using call by reference and call by value.
What is nibble in a byte?
A nibble consists of four bits. There are two nibbles in a byte. For example, 64 is to be represented as 01000000 in a byte (or 8 bits). The two nibbles are (0100) and (0000).
What is nibble swapping mean?
Let’s understand the below example to understand the nibble swapping. Suppose you have a number that has values 100. The 100 is to be represented as 01100100 in a byte (or 8 bits). The two nibbles are 0110 and 0100. After swapping the nibbles, we get 01000110 which is 70 in decimal.
Input : 01100100 || \/ Output : 01000110
C Program to swap two nibbles in a byte
We will use bitwise operators &, |, << and >> to swap the nibbles in a byte. Let see the C program to swap the nibbles,
#include <stdio.h> int main() { unsigned char data = 100; //swapping nibbles data = (((data & 0x0F)<<4) | ((data & 0xF0)>>4)); printf("%u\n", data); return 0; }
Output:
70
Code Explanation:
As we know binary of 100 is 01100100. To swap the nibble we split the operation in two parts, in first part we get last 4 bits and in second part we get first 4 bit of a byte.
First operation:
The expression “data & 0x0F” gives us the last 4 bits of data and result would be 00000100. Using bitwise left shift operator ‘<<‘, we shift the last four bits to the left 4 times and make the new last four bits as 0. The result after the shift is 01000000.
Second operation:
The expression “data & 0xF0” gives us first four bits of data and result would be 01100000. Using bitwise right shift operator ‘>>’ , we shift the digit to the right 4 times and make the first four bits as 0. The result after the shift is 00000110.
After completing the two operation we use the bitwise OR ‘|’ operation on them. After OR operation you will find that first nibble to the place of last nibble and last nibble to the place of first nibble.
01000000 | 00000110 || \/ 01000110
C Program to swap two nibbles in a byte using macro:
#include <stdio.h> //Macro to swap nibbles #define SWAP_NIBBLES(data) ((data & 0x0F)<<4 | (data & 0xF0)>>4) int main() { unsigned char value = 100; //print after swapping printf("%u\n", SWAP_NIBBLES(value)); return 0; }
C Program to swap two nibbles in a byte using function:
Using Call by reference:
#include <stdio.h> void swapNibbles(unsigned char *p) { *p = ((*p & 0x0F)<<4 | (*p & 0xF0)>>4); } int main() { unsigned char value = 100; //swapping the nibbles swapNibbles(&value); printf("%u\n", value); return 0; }
Output:
70
Using Call by value:
#include <stdio.h> unsigned char swapNibbles(unsigned char p) { return ( (p & 0x0F)<<4 | (p & 0xF0)>>4 ); } int main() { unsigned char value = 100; //swapping the nibbles printf("%u\n", swapNibbles(value);); return 0; }
Output:
70