I understand 0u means 0 unsigned, but what does the ~ at the beginning mean? Does it signify inversion in this case or does it mean something else?
4 Answers
It indicates bitwise not; all bits in the integer will be flipped, which in this case produces a number where all bits are 1.
Note that since it is unsigned, if the integer is widened during assignment the extended bits would be 0. For example assuming that unsigned short is 2 bytes and unsigned int is 4:
unsigned short s = ~0u; // 0xFFFF unsigned int i = s; // 0x0000FFFF If you need to invert the bits of some generic numeric type T then you can use the construct ~(T(0)).
This operator is better described in the C Standard than in the C++ Standard
4 The result of the ~ operator is the bitwise complement of its (promoted) operand (that is, each bit in the result is set if and only if the corresponding bit in the converted operand is not set). The integer promotions are performed on the operand, and the result has the promoted type. If the promoted type is an unsigned type, the expression ~E is equivalent to the maximum value representable in that type minus E.
Thus ~0u means the maximum value of an object of type unsigned int when each bit of its internal representation is set to 1.
Consider using the operator that to set for example the first n bits to 1. The expression will look like
~( ~0u << n ) If you want to set n bits starting from m position then you can write
~( ~0u << n ) << m It means a bitwise not which flips all the bits of the integer value by giving you a number with all bits set to 1.
(Assuming a 32 bit uint) 0u 00000000 00000000 00000000 00000000 ~0u 11111111 11111111 11111111 11111111 3 00000000 00000000 00000000 00000011 ~3 11111111 11111111 11111111 11111100 If the machine uses a 2's complement representation for negative integers, then casting ~0u to a signed integer is equivalent to -1. More on this in Stack Overflow question Is there a difference between -1 and ~0?.
It is to invert the values in bits. For example:
00000000000000000001
to
11111111111111111110
This is what ~ does.