Reading Individual Bits in Variables?
coryco2
Posts: 107
Does anyone know a simple way to test the state of an individual bit in a one-byte variable? I would like to be able to test, for example, whether the third bit in the byte is 1 or 0 regardless of the states of the other bits. Any suggestions?
Comments
PUB CheckBit( value, bitNr )
return value & |< bitNr
where value = 0 .. 7 in your case. As parameters in SPIN are LONGs you can also go from 0..31
Explaination:
|< is an operator which shifts a 1 bit set at the least significant bit as much to the left as given by the parameter. For example |< 3
%00000000_00000000_00000000_00000001 shifted left 3 times gives you
%00000000_00000000_00000000_00001000
The next operation is a logical and which gives you back all the bits where the bit of both operands are set to one. If one operand only has 1 bit set, the result shows you if this one bit is set in the other operand regardless of all other bits. For example:
%01111010_11010001_00011001_11011000 &
%00000000_00000000_00000000_00001000 gives you
%00000000_00000000_00000000_00001000
If you use this number in an expression which expects a boolean value, it's the same as TRUE because all values <>0 are TRUE and only 0 is FALSE. So, it's safe to use this function in an IF statement for example.
...