C++ – What does “(int) value & 0x1, (int) value & 0x2, (int) value & 0x4, (int) value & 0x8″ mean?”

bitwise-operatorsc

code

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 either 0 or 1 (these are the bits of the representation). This is the binary representation.

The binary AND (&) takes each of those b pair wise and performing AND on them. This has the following outputs:

0 & 0 = 0
0 & 1 = 0
1 & 0 = 0
1 & 1 = 1

Using powers of 2 (which have only a single bit on) we can isolate and test the individual bits:

  • value & 1 is true when value is odd {1, 3, 5, 7, 9, 11, 13, 15}.

  • value & 2 is true when value/2 is odd {2, 3, 6, 7, 10, 11, 14 ,15}.

  • value & 4 is true when value/4 is odd {4, 5, 6, 7, 12, 13, 14 ,15}.

  • value & 8 is true when value/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.