Reputation: 495
PROGRAMMING LANGUAGE: C
I've a 8 bit data with only 3 bit used, for example:
0110 0001
Where 0 indicate unused bit that are always set to 0 and 1 indicate bits that change.
I want to convert this 0110 0001 8 bit to 3 bit that indicate this 3 used bits.
For example
0110 0001 --> 111
0010 0001 --> 011
0000 0000 --> 000
0100 0001 --> 101
How I can do that with minimal operations?
Upvotes: 0
Views: 1865
Reputation: 33076
You can achieve this with a couple of bitwise operations:
((a >> 4) & 6) | (a & 1)
Assuming you start from xYYx xxxY
, where x
is a bit you don't care about and Y
a bit to keep:
a
will result in xYYx
, then masking with 6
(binary 110
) will make sure only the second and third bit are retained, resulting in YY0
and preventing flipped x
bits from messing up.a & 1
selects the LSB, resulting in Y
.YY0
and Y
are combined using a |
bitwise or, resulting in YYY
.Now you have the 3 bits you asked. But keep in mind that you can't address single bits, so it will still be byte-aligned as 00000YYY
Upvotes: 4
Reputation: 9305
You can get the k'th bit of n: (where n is 011000001)
(n & ( 1 << k )) >> k
(More details about that at StackOverflow)
so you use that to get bit 1,6 and 7 and just add those:
r=bit1+bit6*16+bit7*32
Upvotes: 0