Welcome to MindCipher, a social repository of the world's greatest brain teasers, logic puzzles and mental challenges.

Bit Pair Swap

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


GULSHAN

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

  

GULSHAN

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


Andrew Kesterson

This 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 Kesterson

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

  

Andrew Kesterson

Actually, 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.

  

Ravi

I 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 Elliott

I agree with ravi, your solution doesn't work.


Kai

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


Kevin L Keathley
b = ((a & 0x40) << 1) + ((a & 0x80) >> 1) + 
      ((a & 0x10) << 1) + ((a & 0x20) >> 1) + 
      ((a & 0x4) << 1) + ((a & 0x8) >> 1) + 
      ((a & 0x1) << 1) + ((a & 0x2) >> 1);
  

Kevin L Keathley

^ Long form :-)


justin_wo

Another 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_wo

Sorry typo:

00 ^ 00 is 00


Jesse Salazar

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

Check out other puzzles:
Random  

Like this? You might also like:
What am I?
All Apples
Gold or silver?
Submitted by
Ravi
over 1 year ago
Likes
Difficulty 6.0 ?

Tags
algorithm programming bitwise


Back