I found this piece of code:
enum { IsDynamic = (1U << 0), // ... IsSharable = (1U << 1), // ... IsStrong = (1U << 2) // ... };
What does the (1U << X)
do?
In more detail, 1 << j uses shifting of 1 to generate a bit mask in which only the j -th bit is set. The & operator then masks out the j -bit of counter ; if the result is not zero (which means that the j -th bit of counter was set), the condition is satisfied.
1U is unsigned. It can carry values twice as big, but without negative values. Depending on the environment, when using U, i can be a maximum of either 31 or 15, without causing an overflow. Without using U, i can be a maximum of 30 or 14.
The right shift operator ( >> ) returns the signed number represented by the result of performing a sign-extending shift of the binary representation of the first operand (evaluated as a two's complement bit string) to the right by the number of bits, modulo 32, specified in the second operand.
It sets bitmasks:
1U << 0 = 1 1U << 1 = 2 1U << 2 = 4 etc...
What happens is 1U (unsigned value 1) is shifted to the left by x bits.
The code you posted is equivalent to:
enum { IsDynamic = 1U, // binary: 00000000000000000000000000000001 IsSharable = 2U, // binary: 00000000000000000000000000000010 IsStrong = 4U // binary: 00000000000000000000000000000100 }
Bit shift. Instead of saying a = 1, b = 2, c = 4 they shift the bits. The idea is to pack many flags into one integer (or long).
This is actually a very clean approach.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With