Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does (1U << X) do?

Tags:

c++

I found this piece of code:

enum  {   IsDynamic = (1U << 0),  // ...   IsSharable = (1U << 1), // ...   IsStrong = (1U << 2)    // ... }; 

What does the (1U << X) do?

like image 303
Karl von Moor Avatar asked Jan 24 '10 19:01

Karl von Moor


People also ask

What is the meaning of 1 << J in C++?

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.

What is the value of 1U in C?

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.

What is the meaning of >> operator?

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.


2 Answers

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 } 
like image 69
Philippe Leybaert Avatar answered Sep 29 '22 12:09

Philippe Leybaert


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.

like image 35
Hamish Grubijan Avatar answered Sep 29 '22 13:09

Hamish Grubijan