Please, explain why by doing as follows I'll get a second bit of the number stored in i
in it's internal representation.
(i & 2) / 2;
Please, explain why by doing as follows I'll get a second bit of the number stored in i
in it's internal representation.
(i & 2) / 2;
i & 2
masks out all but the second bit in i
. [1]0
or 2
(binary 00
and 10
respectively).2
gives either 0
or 1
which is effectively the value of the second bit in i
.For example, if i = 7
i.e. 0111
in binary:
i & 2
gives 0010
.0010
is 2
in decimal.2/2
gives 1
i.e. 0001
.[1] &
is the bitwise AND in C. See here for an explanation on how bitwise AND works.
i & 2
masks out all but the second bit.
Dividing it by 2 is the same as shifting down 1 bit.
e.g.
i = 01100010
(i & 2) == (i & 00000010) = 00000010
(i & 2) / 2 == (i & 2) >> 1 = 00000001
The &
operator is bitwise AND: for each bit, the result is 1 only if the corresponding bits of both arguments are 1. Since the only 1 bit in the number 2 is the second-lowest bit, a bitwise AND with 2 will force all the other bits to 0. The result of (i & 2)
is either 2 if the second bit in i
is set, or 0 otherwise.
Dividing by 2 just changes the result to 1 instead of 2 when the second bit of i
is set. It isn't necessary if you're just concerned with whether the result is zero or nonzero.
2
is 10
in binary. &
is a bitwise conjunction. So, i & 2
gets you the second-from-the-end bit of i
. And dividing by 2 is the same as bit-shifting by 1 to the right, which gets the value of the last bit.
Actually, shifting to the right would be better here, as it clearly states your intent. So, this code would be normally written like this: (i & 0x02) >> 1