Bit masking - sanity check

Hello everybody,

I am toying with shift registers (HC595) and trying to move babysteps in bit masking.
I have a set of 8 boolean variables I want to store as a single byte. When the state of one of the boolean variables change, I want only the bit relative to that variable to change, the others being left unchanged.
I arrived at this point:

if (value == 1){
  obyte = obyte | omask;
}
else {
  obyte = 0x00;
}

value is the nth state-boolean
obyte is the storing byte
omask is the mask for the nth value.

This someway works, but when "value" is zero, it obviously resets all the other stored states.
What is the best coding practice for a (simple, I know...) task like this?

Thanks in advance for the help!

Hello, read this for a start: Bitmasks.

Why use 8 boolean variables when you could just use the 8 bits in the byte directly ?

I think that's what OP is attempting to do, perhaps not expressed perfectly:

This is because I receive those values from serial as booleans

"Best" may be subjective, but try:

  if (value == 1) {
    obyte |= omask;
  }
  else {
    obyte &= ~omask;
  }
1 Like

I would perhaps start by putting the booleans in an array. Then you could iterate through the array and set/unset the corresponding bits in the byte

What are you going to do with the byte once its bits have been set to match the booleans ?

This works perfectly, thanks!

Get the compiler to do it for you...

typedef struct {
  uint8_t a : 1;
  uint8_t b : 1;
  uint8_t c : 1;
  uint8_t d : 1;
  uint8_t e : 1;
  uint8_t f : 1;
  uint8_t g : 1;
  uint8_t h : 1;
}
bits;

void setup(void)
{
  bits value;

  value.b = 1;
  value.b = 0;
}
1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.