Reputation: 846
I have a byte A and byte B. I am looking for byte C which is every other bit from A and every other bit from B. So if A = 10011010 and B = 01110010 then C would be 10110101 where 1011 is every other bit from A and 0101 is every other bit from B. Can anyone help me with this?
Upvotes: 2
Views: 270
Reputation: 8821
$a = 154; //10011010
$b = 114; //01110010
$expected = 181; //10110101
$result = (($a>>1)&1)+(($a>>2)&2)+(($a>>3)&4)+(($a>>4)&8) << 4
| (($b>>1)&1)+(($b>>2)&2)+(($b>>3)&4)+(($b>>4)&8);
echo $expected == $result;
Let me think about it for a little while, this could be done more efficiently...
Another one:
$a = 154; //10011010
$b = 114; //01110010
$expected = 181; //10110101
$result = ($a&0x80)+(($a<<1)&0x40)+(($a<<2)&0x20)+(($a<<3)&0x10)+
(($b>>4)&0x8)+(($b>>3)&0x4)+(($b>>2)&0x2)+(($b>>1)&0x1);
echo $expected == $result;
...And now I notice the C# tag...
Upvotes: 0
Reputation: 838326
Try this:
byte C = (byte)(
(A & 0x80) |
((A & 0x20) << 1) |
((A & 0x08) << 2) |
((A & 0x02) << 3) |
((B & 0x80) >> 4) |
((B & 0x20) >> 3) |
((B & 0x08) >> 2) |
((B & 0x02) >> 1));
See it working online: ideone
Upvotes: 2
Reputation: 437386
Something like this should do it:
var nibble1 = ((a & 0x80) << 3) | ((a & 0x20) << 2) |
((a & 0x08) << 1) | (a & 0x02);
var nibble2 = ((b & 0x80) << 3) | ((b & 0x20) << 2) |
((b & 0x08) << 1) | (b & 0x02);
var result = (nibble1 << 4) | nibble2;
For each input byte you take the "first" (actually it's customary to count starting from the other end, but I 'll go with that sounds more straightforward here) byte, shift it 3 places (to make room behind it for the others), add the "third" byte (shifting it two places) etc.
Then you shift the first nibble you just computed four places (to make space for the second) and stick them together.
Upvotes: 0