 # bitwise operation (C++ vs C vs Arduino)

hi all,
quick question (maybe i am doing something wrong)

i am trying to use bitwise operators to convert red green and blue values to an unsigned long, in C and C++ i get the expected output, in Arduino IDE, i get some odd number. see below

C++

``````int r = 255;
int g = 154;
int b = 53;
unsigned long color = ((r & 0x0ff)<<16)|((g & 0x0ff)<<8)|(b&0x0ff);
#include <iostream>
int main(){std::cout << color;}
``````

color = 16751157

C(vanilla)

``````int r = 255;
int g = 154;
int b = 53;
unsigned long color = ((r & 0x0ff)<<16)|((g & 0x0ff)<<8)|(b&0x0ff);
#include <stdio.h>
int main(void)
{
printf("%lu", color);
return 0;
}
``````

color = 16751157

Arduino IDE

``````int r = 255;
int g = 154;
int b = 53;
unsigned long color = ((r & 0x0ff)<<16)|((g & 0x0ff)<<8)|(b&0x0ff);

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

void loop() {
delay(1000);
Serial.println(color);
}
``````

color = 4294941237

any insight wold be very much appreciated

in reference to http://forum.arduino.cc/index.php?topic=72631.0 this has been solved

``````int r = 255;
int g = 154;
int b = 53;
/**
** you need to implement unsigned long casting
**
**unsigned long color = ((r & 0x0ff)<<16)|((g & 0x0ff)<<8)|(b&0x0ff);
**//
unsigned long color = (unsigned long)r << 16 | (unsigned long)g << 8 | (unsigned long)b;

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

void loop() {
delay(1000);
Serial.println(color);
}
``````

Your first two examples were compiled for a machine with 32 bit "int"s, I'll bet.

255 = 0xff
154 = 0x9a
53 = 0x35
0xff9a35 = 16751157

0xffff9a35 = 4294941237

Where’d the extra ff come from?

(r & 0x0ff)<<16
Ah, I see from the other thread - 0x00ff is an int, telling it to shift 16 bits shifts it right out of the int.

0x9a sign-extended, 0xff sign-extended