top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Swap the first 8 bits and the last 8 bits of 16-bit value

+8 votes
995 views

For example, 00000001 11001100 becomes 11001100 00000001;

unsigned short swap_bytes(unsigned short x) {

}

posted Feb 6, 2014 by Manu Lakaster

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

2 Answers

+2 votes
 
Best answer

Method 1:

extract the high byte hibyte = (x & 0xff00) >> 8;
extract the low byte lobyte = (x & 0xff);
combine them in the reverse order x = lobyte << 8 | hibyte;

Method 2:

typedef union mini
{
    unsigned char b[2];
    unsigned short s;
} micro;

unsigned short swap_bytes(unsigned short x) 
{
    micro y;
    y.s = b;
    unsigned char tmp = y.b[0];
    y.b[0] = y.b[1];
    y.b[1] = tmp;
    return y.s
}
answer Feb 6, 2014 by Kumar Mitrasen
Can  u explain your code for beginner please...
–1 vote

Mask first 8 bits so you will get second 8 bits and mask second 8 bits so you will get first 8 bits. Now do OR for these two then you will get swapped number.

(num & 0x00FF ) || (num & 0xFF00 ) .

answer Feb 6, 2014 by sivanraj
I see. Well I think U mean "return (x & 0x00FF ) || (x & 0xFF00 );" Right?
yes............
Similar Questions
+4 votes

How to swap ith and jth Bits for a 32-Bit Integer?

+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 .

+2 votes

How can I wwap value two variables without using third variable or +/- operator?

+4 votes

Complexity should be less than O(n);

...