Yaro
Yaro

Reputation: 495

Convert an 8 bit data to 3 bit data

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

Answers (2)

Stefano Sanfilippo
Stefano Sanfilippo

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:

  1. left shift by 4 of 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.
  2. a & 1 selects the LSB, resulting in Y.
  3. the two parts, 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

Ole Albers
Ole Albers

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

Related Questions