A solution from a top answer is
To check a bit, shift the number x to the right, then bitwise AND it:
bit = (number >> x) & 1;
That will put the value of bit x into the variable bit.
What confuses me is this, when assuming the following:
unsigned number = 5; //0101
int x = 2; //
After a shift (number >> x)
we get 0001
. But we shifted off bits 1 and 2 and so when we do the bitwise AND, aren't we doing it against the third bit and not the second, where x = 2
? Doesn't this mean that if I want to check if bit x
is set, shouldn't I do:
bit = (number >> (x - 1)) & 1);