In one line of C or Java, how would you swap every pair of bits in a byte? That is, swap bits 0 and 1, 2 and 3, 4 and 5, 6 and 7.

Example: `0110 1010`

becomes `1001 0101`

.

See solution.

`x_after = (((x_before & 0x55) << 1) | ((x_before & 0xAA) >> 1))`

`((x_before & 0x55) << 1)`

takes bits {0,2,4,6} and shifts them left, while `((x_before & 0xAA) >> 1)`

takes bits {1,3,5,7} and shifts them right. Finally, the two resulting values are OR'd together.

## Comments

Sign uporlog in with Facebookto comment.GULSHANi got the answer . let C be the input and C_after be the output

C_after = ( ( ( C >> 1) || 128 ) & ( ( C << 1) || 1 ) ) );

please comment if it fails at any input.

GULSHANplease note in my solution it was not || (logical OR) but but | (bitwise OR) (typing mistake)

Andrew KestersonThis is a really complicated answer to a really simple question.

What you want is to bitwise invert the value, or create its "complement", swapping every 0 for a 1 and vice versa. Every language known to man has this, a single character operation. It looks like this:

x = ~x

... and lo and behold, X will contain the inverse of its prior self.

Andrew KestersonActually, nevermind, I misread the question. I didn't realize the goal was to swap individual pairs of bits.

Andrew KestersonActually, no, I'm still right. Complement will produce the desired result whether you're looking at pairs or individual bits, base 2 doesn't have enough numerals for that choice to make a difference.

RaviI don't think that works. For example, if you have

`0000 0001`

, your solution will give you`1111 1110`

, but the actual solution would be`0000 0010`

.Jay ElliottI agree with ravi, your solution doesn't work.

KaiI think the example is misleading, the example imply's that i should replace 1 => 0 and 0 => 1

Kevin L KeathleyKevin L Keathley^ Long form :-)

justin_woAnother solution but not as clean (I used two lines but it's just for substitution so its easier to read but it can be done with 1 line).

checker = (byte ^ (byte >> 1)) & 0b1010101; x_after = (checker + checker<<1)^byte;

The idea is that: 01 ^ 11 = 10 10 ^ 11 = 01 11 ^ 00 = 11 00 ^ 00 = 11

So we want to find the pairs that are different and then apply the 11 xor to them and then find the pairs that are same and then apply the 00 xor to them.

justin_woSorry typo:

00 ^ 00 is 00

Jesse Salazarx_swap = ( (x>>1) & 0x55 ) | ( (x<<1) & 0xAA )