top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

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

+3 votes
364 views
How to swap lower byte (0-7) with the higher one (8-15) using C?
posted Apr 2, 2015 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+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 
answer Apr 6, 2015 by Arshad Khan
Similar Questions
+3 votes

e.g. Suppose I enter a string : Ram and Shyam likes Ramesh then the output should be Ramesh and Shyam likes Ram.
Here first word Ram is swapped with Ramesh .

+3 votes

Hamming distance between two binary numbers is the number of different bits between two numbers. With respect to 0, how many numbers are there with 10 as the hamming distance and can be represented using 15 bits.

...