The "value" ranges from 0 to 15 (its possible values). When will those 4 "if" conditions be met? If my (int)value = 2 does this mean 0010?
if ((int)value & 0x1)
{
//statement here
}
if ((int)value & 0x2)
{
//statement here
}
if ((int)value & 0x4)
{
//statement here
}
if ((int)value & 0x8)
{
//statement here
}
Best Answer
Each number can be expressed as
value = b0*2^0 + b1*2^1 + b2*2^2 + b3*2^3 + ...
with each b being either0
or1
(these are the bits of the representation). This is the binary representation.The binary AND (
&
) takes each of thoseb
pair wise and performing AND on them. This has the following outputs:Using powers of 2 (which have only a single bit on) we can isolate and test the individual bits:
value & 1
is true whenvalue
is odd {1, 3, 5, 7, 9, 11, 13, 15}.value & 2
is true whenvalue/2
is odd {2, 3, 6, 7, 10, 11, 14 ,15}.value & 4
is true whenvalue/4
is odd {4, 5, 6, 7, 12, 13, 14 ,15}.value & 8
is true whenvalue/8
is odd {8, 9, 10, 11, 12, 13, 14 ,15}.The 0x prefex on the numbers means it should be interpreted as a hexadecimal number. It is a bit superfluous when you only go up to 0x8 but tells maintainers it is probably used as a bitmask.