# How to swap lower byte (0-7) with the higher one (8-15) using C?

81 views
How to swap lower byte (0-7) with the higher one (8-15) using C?
posted Apr 2, 2015

+1 vote

Its very simple. You can achieve this by using bit wise operator.
Have a look.

Input :

``````int16_t num = 127;       // bit representation of 127 (0 0 0 0 0 0 0 0    0 1 1 1 1 1 1 1)
num = (num << 8 | num >> 8);       //This is what you need to do. This will swap the 0-7th bit to 8-15th bit

/*
If you print the bit of "num" after  applying the left shift (<<) and right shift (>>) operation you will get the
following output.
*/
(0 1 1 1 1 1 1 1    0 0 0 0 0 0 0 0)
``````

Here the program for that, (Tested):

``````#include <stdio.h>
#include <stdint.h>  // For int16_t

/*
Function to print the bits of the given number.
*/
void show_bit(int16_t n)
{
int i = 16;
while(i)
(n >> (i-- - 1) & 1) ? printf("1 ") : printf("0 ");

printf("\n");
}

int main()
{
int16_t number = 127;  // You can change the number as per your requirement.

printf("Before swaping the bits of (%d) :\n", number);
show_bit(number);

number = (number << 8 | number >> 8);

printf("After swaping the bits of (%d) :\n", number);
show_bit(number);

return 0;
}
``````

Output:

``````Before swaping the bits of (127) :
0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1
After swaping the bits of (32512) :
0 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0
``````