Hex adition and bit shifting strange results

I am working an a little pice of code to sweep through a range of colours using NeoPixel LED's ultimatly with an Addafruit Gemma. at the moment I am using a Leonardo to fault find the code as the outputs from the Gemma where not consistant.
using the Leonardo has shown me that the method I have used to generate the referance codes for the colour required is not working as I would expect.
The code generates the output I would be expecting until we reach 0x80 when bit shifted it adds 0xffff0000 to the total. :~
I would expect to see.
7E00 then 7F00 then 8000 then 8100
being presented by 'myColor' NOT
7E00 then 7F00 then FFFF8000 then FFFF8100

Has any one got any good reasons why this happens and can it be fixed?

void setup() {
  Serial.begin(9600);
}
void loop() {  
  for( int color = 0x00; color < 0xff; color += 1) {
      long myColor = color << 8;
      Serial.println(color,HEX);
      Serial.println(myColor,HEX);
      Serial.println(myColor,BIN);
      delay(100);  
  }  
  delay(1000);
}

output from code using serial monitor:

7D
7D00
111110100000000
7E
7E00
111111000000000
7F
7F00
111111100000000
80
FFFF8000
11111111111111111000000000000000
81
FFFF8100
11111111111111111000000100000000
82
FFFF8200
11111111111111111000001000000000
83
FFFF8300

Good reason - sign extension.

Thanks that sorted it. :slight_smile:

output now as expected.

void setup() {
  Serial.begin(9600);
}
void loop() {  
  for( int color = 0x00; color < 0xff; color += 1) {
      long myColor = (unsigned int)color << 8;
      Serial.println(color,HEX);
      Serial.println(myColor,HEX);
      Serial.println(myColor,BIN);
      delay(100);  
  }  
  delay(1000);
}

well not quite
if you bit shift it 16, that is moving the two hex carecters just two mor spaces to the left the output completely vanishes
e.g. I expect
A1
A10000
101000010000000000000000
A2
A20000
101000100000000000000000
etc

what I get now is:
A1
0
0
A2
0
0
A3
0
0
etc

Any Ideas or work arounds avalable (works fine bit shifting all the way from 1 to 15 places but not from 16 up) or work arounds avalable?

void setup() {
  Serial.begin(9600);
}
void loop() {  
  for( int color = 0x00; color < 0xff; color += 1) {
      long myColor = (unsigned int)color << 16;
      Serial.println(color,HEX);
      Serial.println(myColor,HEX);
      Serial.println(myColor,BIN);
      delay(100);  
  }  
  delay(1000);
}

Try casting to a data type longer than 16 bits.