Testing for a particular bit in a byte value
DavidM
Posts: 630
Hi,
How do I test for particular "BIT" of a value is set to 1 or 0??
e.g. I have a 4 bit value ..
Value := $0111
I want to test if a particular bit of any of its 4 bits) , to see if its a 1 or a 0
Lets say I want to check the 3rd bit ( starting from the left )
How do I do this? Do I use BITWISE DECODE?? or maybe bitwise AND?
Thanks
Dave M
How do I test for particular "BIT" of a value is set to 1 or 0??
e.g. I have a 4 bit value ..
Value := $0111
I want to test if a particular bit of any of its 4 bits) , to see if its a 1 or a 0
Lets say I want to check the 3rd bit ( starting from the left )
How do I do this? Do I use BITWISE DECODE?? or maybe bitwise AND?
Thanks
Dave M
Comments
Would this be what I need to do ( I don't see why I would have to shift left at all)
e.g. To test the first ( Leftmost) bit
MyValue := %1010
IF MyValue & %1000 == %1000
This if statement above would test TRUE as the first bit is 1
or to test the 2nd bit from the left
MyValue := %1010
IF MyValue & %0100 == %0100
would return FALSE as the 2nd bit is 0
etc..
Regards
Dave M
Your idea of shifting left by the number of bits makes sense so you can see what bit you are testing for as well as keeping the code generic.
Thanks
Dave M
wouldn't this do,
IfNot Myvalue>>4
myValue:=%0100
and you did
if myValue>>2
then it would work but if you had
myValue:=%1100
then it wouldn't work.
You could do
if (myValue>>2)&1
You would have to check to see exactly what 'ifnot' checks for as well.
In 99% of cases that's exactly what you do.· Better yet, set up a named constant for the %1000.
If you did have to be adaptable to check any bit, SPIN has an operator that sets a single bit by number.
|<0 gives %1
|<3 gives %1000
|<31 gives %10000000_00000000_00000000_00000000
So you could do:
MyValue := %1010
IF Myvalue &·|<3
▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
Help to build the Propeller wiki - propeller.wikispaces.com
Play Defender - Propeller version of the classic game
Prop Room Robotics - my web store for Roomba spare parts in the UK
So what you first said was :-
Mybit :=(myvalue>>Mybit)&1
I think.
regards
Ron
Any nonzero result is true though you could promote it to a true true [noparse]:)[/noparse] with:
use it like this:
The above statement does not need to compare testbit to a true or false because the result of testbit is true or false. If the bit is set then the result is true.
*Peter*
Thanks everyone!
I think that BITWISE DECODE is the go for this!
I just have to remember that the first bit ( starting from the RIGHT ) is bit 0 not 1
|<0 First bit starting from the right
|<1 2nd bit
|<2 3rd bit
|<4 4th bit etc..
So..
IF MyValue |<3
would result in TRUE if the 4th bit from the right is set to 1
is this correct?
regards
Dave M
that should be..
IF MyValue & |<3
would result in TRUE if the 4th bit from the right is set to 1
Dave M
▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
Paul Baker
Propeller Applications Engineer
Parallax, Inc.