0

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?

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
jubibanna
  • 1,095
  • 9
  • 21
  • 7
    With `if((x & 3) == 2)` and no shifting is needed, only masking to keep the 2 ls bits. – Weather Vane Feb 21 '20 at 08:16
  • Thank you, it makes sense! From wiki: "if both bits in the compared position are 1, the bit in the resulting binary representation is 1 (1 × 1 = 1); otherwise, the result is 0 (1 × 0 = 0 and 0 × 0 = 0)". So it makes sense that you & with 3 since this will only compare the first two bits and make the rest 0! – jubibanna Feb 21 '20 at 08:21
  • 1
    That's right: C doesn't accept binary notation, and decimal `3` is binary `11`. When you AND that with another number, the least 2 bits are preserved, and the rest are zeroed. For a larger value I might use hexadecimal for clarity, but `3` is the same in both notations. – Weather Vane Feb 21 '20 at 08:22

1 Answers1

0

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 oring 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
Swedgin
  • 815
  • 1
  • 11
  • 20