bit shifting unsigned long


I’ve a problem with bitshifting values. According to the reference a long can story 32 bit ( 4 bytes ). I would like to store an RGB value ( 3 bytes ) in a long, with bitshifting.

However, shifting 1 bit higher than 14 bits ( 1 << 15 ) doesn’t seem to work.

I’ve made a test application, code below.
color_in and colour_out should output the same value (1), but this goes wrong when ana_0 is above 14 ( shifting with 14 bits ).

unsigned long ana_0;

void setup()
{ digitalWrite(13, HIGH);

void loop()  
{ ana_0 = analogRead(0)>>5; // # between 0-32
  unsigned long color_in  = 1 << ana_0;
  unsigned long color_out = color_in >> ana_0;

I believe the problem is that the calculation 1 << ana_0 is done using integer math because the 1 is an integer. The result is stored in an unsigned long, but only after it’s overflowed. Try declaring the constant 1 as an unsigned long: 1UL

Thank you, that solved the problem.