According to the documentation it is possible to shift up to 32 bits, however when using long variables and shifting 15 or more I get incorrect results. This happens both with signed and unsigned longs. Shifting to the right (>>) provides the correct results.
Is there perhaps a bug in the bit shift code? Board used: Arduino Uno
The code (at bottom) uses 2 methods to multiply / divide by 2: 1. using "ordinary" calculations and 2. bit shift operations for both signed and unsigned longs.
Program output:
Left column, bits to shift
middle column, expected result
right column, bit shift result
Unsigned Long up / left
0 1 1
1 2 2
2 4 4
....
14 16384 16384
15 32768 4294934528
16 65536 0
....
30 1073741824 0
31 2147483648 0
Signed Long up / left
0 1 1
1 2 2
2 4 4
...
14 16384 16384
15 32768 -32768
16 65536 0
...
29 536870912 0
30 1073741824 0
....
void setup()
{
Serial.begin(115200);
Serial.println("Unsigned Long up / left");
for (int n=0; n < 32; n++)
{
unsigned long Power = 1;
for (int m=0; m < n; m++)
{
Power *= 2;
}
unsigned long BitShift = 1 << n;
Serial.print(n);
Serial.print("\t ");
Serial.print(Power);
Serial.print("\t ");
Serial.print(BitShift);
Serial.println();
}
Serial.println();
Serial.println("Signed Long up / left");
for (int n=0; n < 31; n++)
{
long Power = 1;
for (int m=0; m < n; m++)
{
Power *= 2;
}
long BitShift = 1 << n;
Serial.print(n);
Serial.print("\t ");
Serial.print(Power);
Serial.print("\t ");
Serial.print(BitShift);
Serial.println();
}
Serial.println();
Serial.println("Unsigned Long down / right");
for (int n=31; n >= 0; n--)
{
unsigned long Power = 2147483648;
for (int m=0; m < n; m++)
{
Power /= 2;
}
unsigned long BitShift = 2147483648 >> n;
Serial.print(n);
Serial.print("\t ");
Serial.print(Power);
Serial.print("\t ");
Serial.print(BitShift);
Serial.println();
}
Serial.println();
Serial.println("Signed Long down / right");
for (int n=30; n >= 0; n--)
{
long Power = 1073741824 ;
for (int m=0; m < n; m++)
{
Power /= 2;
}
long BitShift = 1073741824 >> n;
Serial.print(n);
Serial.print("\t ");
Serial.print(Power);
Serial.print("\t ");
Serial.print(BitShift);
Serial.println();
}
}
void loop()
{
}