What does (1U << X) do?

Viewed 48951

I found this piece of code:

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

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

5 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
}

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.

<< is the bitshift operator. It will take the bits in the left side and shift them by an amount specified by the right side. For example:

1 << 1    -> 0b0001 << 1     =>   0b0010  
1 << 2    -> 0b0001 << 2     =>   0b0100

etc.

1U is an unsigned value with the single bit 0 set, and all the other bits cleared. The << operator means "shift to the left". 1U << 0 means create a value with bit 0 set; 1U << 1 means create a value with bit 1 set; etc.

That snippet

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

declares an enumeration with values which are powers of 2. To be used presumably as masks on a value which contains multiple flags.

So for example a value representing something that IsDynamic and IsSharable is

unsigned value = IsDynamic | IsSharable; // could use + as well

And to test if the value IsStrong

if (value & IsStrong) { ... }
Related