Left Shift more than 15 bits fails?

Hi,
Arduino 1.8.13, Board Arduino Mega 2056.
I need to set individual bits in a int32 (long) value. For that, I use the left-shift like
1 << 30 which is expected to shift a 1 bit into the msb-1 position in the 32 bits value.
The result was 0 (zero).
I tested the command and found out that it will not correctly shift left more than 15 positions.
The bitSet() command seems OK.
Unless I'm doing something very wrong, this is a bug.
Any idea

From the official Arduino reference for Bitwise Operators:

variable : Allowed data types: byte, int, long
number_of_bits : a number that is < = 32. Allowed data types: int

The test program:
long val = 0;
int i ;
for (i = 0 ; i <32 ; i++)
{
val = 1 << i;
Serial.print(i); Serial.print(" "); Serial.println(val, BIN);
}

The outcome:
0 1
1 10
2 100
3 1000
4 10000
5 100000
6 1000000
7 10000000
8 100000000
9 1000000000
10 10000000000
11 100000000000
12 1000000000000
13 10000000000000
14 100000000000000 // This is 0x4000
15 11111111111111111000000000000000 // This is 0xFFFF8000 (a negative number).
16 0
17 0
18 0
19 0
20 0
21 0
22 0
23 0
24 0
25 0
26 0
27 0
28 0
29 0
30 0
31 0

You are using a long

If you want to set the bits in a long you could always use bit masking

long aLong;

void setup()
{
  Serial.begin(115200);
  while (!Serial);
  aLong |= 0b10000000000000000000000000000000;
  Serial.println(aLong, BIN);
}

void loop()
{
}

Just use 1L << 30 or 1UL << 30.

Expressions (and so numbers) are evaluated as 16 bit by default,
if the operand is given an explicit type, it is used.

If you want even more bits then the long long variable type gives you 64 bits to play with. Very useful for certain types of RFID cards.

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.