c++bitwise-or

logic behind assign binary literals to an int


Found that logic on a code and don't get the reason behind that; why use it instead of assign normal int? (its a character controller in a 3D environment)

// assumes we're not blocked
int blocked = 0x00;

if ( its_a_floor )
        blocked |= 0x01;

if ( its_a_wall )
        blocked |= 0x02;

Solution

  • 0x00 is a "normal int". We are used to base 10 representations, but other than having 10 fingers in total, base 10 is not special. When you use an integer literal in code you can choose between decimal, octal, hexadecimal and binary representation (see here). Don't confuse the value with its representation. 0b01 is the same integers as 1. There is literally no difference in the value.

    As a fun fact and to illustrate the above, consider that 0 is actually not a decimal literal. It is an octal literal. It doesn't really matter, because 0 has the same representation in any base.

    As the code is using bit-wise operators it would be most convenient to use a binary literals. For example you can see easily that 0b0101 | 0b10101 equals 0b1111 and that 0b0101 & 0b1010 equals 0b0000. This isn't that obvious when using base 10 representations.

    However, the code you posted does not use binary literals, but rather hexadecimal literals. This might be due to the fact that binary literals are only standard C++ since C++14, or because programmers used to bit wise operators are so used to hexadecmials, that they still use them rather than the binary.