Why is 1<<16 = 0?

I am a bit confused by this strange problem which I am encountering.

If I do this:

long value = 1<<16;
Serial.println(value);

0 is printed at the console. At first I thought it might be because a long isn’t 4 bytes as the manual says. But if I do

long value = pow(2,16);
Serial.println(value);

65536 is printed at the console.
If I do

long value = 1<<8;
Serial.println(value);

I get the correct value (256).

My question is, why does bitshifting not work as it should? Am I doing something wrong?

0000 0000 0000 0001

Shift 1 to the left 16 times and that 1 falls off because 1 is assumed to be an int.

Edit: Better explanation below

the_marsbar:
I am a bit confused by this strange problem which I am encountering.

If I do this:

long value = 1<<16;

Serial.println(value);



0 is printed at the console.
My question is, why does bitshifting not work as it should? Am I doing something wrong?

Because the expression (1 << 16) is evaluated as an ‘int’ expression, and ints are 16-bits. You want to make sure it is done as a long via:

long value = 1L << 16;

or

long value = ((long)1) << 16;

Arrch: Yes, if it was a 16 bit data type. However, long is 32 bit.

MichaelMeissner: Okaaaaaay. I did not know that. Thanks for clarifying.