 # bit math problem - left and right shift rgb color

I try to store RGB color in an unsigned long (I think thats 4 bytes on Arduino).

I’ve based my code on two examples from Processing:
http://processing.org/reference/rightshift.html
http://processing.org/reference/leftshift.html

If I do this 255 << 8 I get a a hex code #FFFF00, while I expect #00FF00.
It seems kind of strange to me, but maybe I miss something essential?

Below the code that I use to debug.

``````//http://processing.org/reference/rightshift.html
//http://processing.org/reference/leftshift.html

void setup()
{ Serial.begin(9600);
}

void loop()
{ byte inputr = 0;
byte inputg = 255;
byte inputb = 0;

Serial.print("input r: ");
Serial.print(inputr,DEC);
Serial.print(" input g: ");
Serial.print(inputg,DEC);
Serial.print(" input b: ");
Serial.println(inputb,DEC);

unsigned long c = inputr << 16 | inputg << 8 | inputb;

Serial.print("output HEX: ");
Serial.println(c,HEX);
//Serial.print("output BIN: ");
//Serial.println(c,BIN);

byte r = (c >> 16) & 0xFF;
byte g = (c >> 8) &  0xFF;
byte b = c & 0xFF;

Serial.print("r: ");
Serial.print(r,DEC);

Serial.print(" g: ");
Serial.print(g,DEC);

Serial.print(" b: ");
Serial.println(b,DEC);

Serial.println("====================");
delay(500);
}
``````
``````  unsigned long c = inputr << 16 | inputg << 8 | inputb;
``````

The inputr << 16 operation is shifting a byte beyond what an int can hold. This results in on overflow of the signed int intermediate result. Storing this overflowed int in an unsigned long causes the results you see. You need to use a cast to tell the compiler to store the intermediate result in a larger register.

``````  unsigned long c = (unsigned long)inputr << 16 | (unsigned long)inputg << 8 | (unsigned long)inputb;
``````

Thank you. That works! I forgot about intermediate result.