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.
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
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.
please note in my solution it was not || (logical OR) but but | (bitwise OR) (typing mistake)
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.
Actually, nevermind, I misread the question. I didn't realize the goal was to swap individual pairs of bits.
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.
I don't think that works. For example, if you have
0000 0001, your solution will give you1111 1110, but the actual solution would be0000 0010.I agree with ravi, your solution doesn't work.
I think the example is misleading, the example imply's that i should replace 1 => 0 and 0 => 1
^ Long form :-)
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.
Sorry typo:
00 ^ 00 is 00