bit manipulation - Check if bit has toggled in C -
i working on bitwise manipulation (in c) , wanted know how check if bit has toggled between previous value , new value.
example : oldvalue = 0x0ff //0000 1111 1111 in binary newvalue = 0x100 //0001 0000 0000 in binary
in example want check if bit8 (9th bit) has toggled 0 1.
i know if want know if bit set, can use :
value & (1 << 8)
so, correct ? :
if( (oldvalue & (1 << 8)) == (newvalue & (1 << 8)) ) //return 0 if toggled
you can in 2 steps:
first, use xor
find all bits have toggled:
int alltoggled = oldvalue ^ newvalue;
then mask bit want keep - example, shifting alltoggled
right, target bit @ position zero, , mask 1
:
int targetbittoggled = (alltoggled >> 8) & 1;
now combine these 2 expressions single condition:
if ((oldvalue ^ newvalue) & (1 << 8)) { // ... bit @ position 8 has toggled }
note instead of shifting xor
-ed values right shifted bit mask left.
Comments
Post a Comment