# Encode & decode boolean values into a single integer?

I'm trying to record the state of some pins over time. To save memory, I'm thinking about encoding the pin states into a single integer, like this:

Pin 1: TRUE
Pin 2: FALSE
Pin 3: FALSE
Pin 4: TRUE

Pin 1 = 1, Pin 2 = 2, Pin 3 = 4, Pin 4 = 8
1 + 0 + 0 + 8
Result: 9

This is pretty efficient. But how do I decode the pin states from this best? Or do you recommend a better way to do this?

use the AND operator.

for example:

pin 2's state would be (result & 0x02)?TRUE:FLASE

• It took me a minute (well, more like 5 ;) ) to figure out these are hex values, but the solution is simple and working perfect. Thank you! Jul 8, 2017 at 18:06

You are almost there with that. Personally I'd use OR not +:

This is a better way of defining the pins instead of using 1, 2, 4 etc. It results in the same thing, but you can see the bit number in there. The << is left shift.

#define PIN0 (1 << 0)
#define PIN1 (1 << 1)
#define PIN2 (1 << 2)
#define PIN3 (1 << 4)

Now you can combine:

uint8_t val = PIN0 | PIN3; // 9

And you can check if one is set:

if (val & PIN3) {
// ....
}

To loop through the pins you can use the << again:

for (uint8_t pin = 0; pin < 8; pin++) {
if (val & (1 << pin)) {
// ....
}
}

etc.

• Pretty cool. I will keep that in mind as another great solution, thank you for your help. Jul 8, 2017 at 18:06