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

+8 votes
256 views

For example, 00000001 11001100 becomes 11001100 00000001;

unsigned short swap_bytes(unsigned short x) {

} posted Feb 6, 2014
Share this question

## 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;
unsigned short s;
} micro;

unsigned short swap_bytes(unsigned short x)
{
micro y;
y.s = b;
unsigned char tmp = y.b;
y.b = y.b;
y.b = tmp;
return y.s
}
`````` answer Feb 6, 2014
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
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 .

+4 votes

Complexity should be less than O(n);

+2 votes

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