Go Down

Topic: read specific bits of a byte? (Read 478 times) previous topic - next topic

tempalte

I am reading in a single byte over TWI.  Each bit stands for something.  I want to be able to read that byte into a data structure, then be able to reference each bit.  I had thought of something like this

struct {
 uint8_t key1:1;
  uint8_t key2:1;
  uint8_t key3:1;
  uint8_t key4:1;
  uint8_t key5:1;
  uint8_t key6:1;
  uint8_t key7:1;
  uint8_t key8:1;
} keys;

structs keys mykeys;

mykeys = SOME BYTE I HAVE.

Serial.print(mykyes.key1);  // would print a zero or one.

But the above doesn't work.  I think I an misunderstanding how struct works.  Anyone have any thoughts on what would be the simplest way to get the value of each bit?

thanks
chad

wandrson

I would use something like the following to test a given bit specified by n where 0 <= n <= 7

value = (keys >> n) & 1;

With this expression value will be either 0 or 1 depending upon what the bit contained.

jims

tempalte has got a lot of the right parts, just not all together.

The packed bitfield structure is correct. That will let you access the 8 bits of the byte individually. But if you want to assign a byte into it, then you either need to put it inside a union or do some typecasting.

For whatever reason, it is not the habit of Arduino programmers or the avr-gcc people to use bit structures. They tend to shift and mask. At a first glance, the object code is about the same so it is a matter of preference.  (Personally, I like bit structs for fixed structures, but I don't code that way here.)

Go Up