1

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?

2 Answers 2

0

use the AND operator.

for example:

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

1
  • 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!
    – Esshahn
    Jul 8, 2017 at 18:06
5

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.

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.