How do I bitshift so I only need to compare the first two digits in a number? Say I want to compare 10101011010
the last two bits and make sure it's 10
.
How would I do that?
How do I bitshift so I only need to compare the first two digits in a number? Say I want to compare 10101011010
the last two bits and make sure it's 10
.
How would I do that?
If you want to check if certain bits are set in an integer, you'd use the binary and
operator (&
) and a mask. In the mask you set the bits you want to check and then use this mask to separate the bits you want to check.
So in your example:
val = b10101011010
And you want to make sure the last 2 bits are 10
:
y = b10 = 0x02 = 2
than you make the mask so it selects the last 2 bits:
mask = b00000000011 = 0x03 = 3
(I'd use the hex notation to make it more clear)
or you could use bitshifting:
mask = (0x01 << 0) | (0x01 << 1)
(setting bit 0 and bit 1 and or
ing them together)
Now we use the binary and
operator:
val = b10101011010
mask = b00000000011
& -----------------
res = b00000000010
--> now we have our bits we are interested in
and we compare res
with the value you want them to be:
if (res == y)
// -> good
else
// -> bad