3

I want to do some bitwise manipulation on GPIO result, suppose I have three variables to define whether the state of some GPIO devices are on or off:

mask          : 1 means bit is set, and need to be calculate
value         : real gpio value 0 / 1
active_level; : 1 means high active, 0 means low active

suppose I have:

mask  : 0010 0001
value : 0000 0001
active: 0000 0001

is there any good way (at this moment I'm thinking about looping) to get the result based on the active level? in above case, bit0 is active high and bit5 is active low, and since bit0 value is high and bit 5 is low, thus the result is:

result: 0010 0001 

later on, what I want to do is to check whether result == mask, if yes means GPIO devices state is on (e.g two buttons are pressed together)

Thanks

user430926
  • 4,017
  • 13
  • 53
  • 77

1 Answers1

3

You may consider the following bit manipulations.

Convert value into "1 means active" format

value_in_activeness = value ^ (~active);

This operation turns the format from "1 is high, 0 is low" to "1 is active, 0 is not active".

active represents "which bits are active-high and which are active-low". Conveniently, its complement ~active means "which bits I want to convert and which bits I want to keep". The XOR operation ^ does the actual conversion.

In your example, value_in_activeness will become 1111 1111. But don't worry, because we have the next step.

Mask out the "I don't care" bits

bits_I_care = value_in_activeness & mask;

Using & to do bit masking is so basic that I don't know what or how to explain.

In your example, the result is 0010 0001.