Strange behavior converting HEX to RGB
I'm trying to convert a HEX color code to RGB but when I run the code on Arduino, it doesn't pick up the RED.
Am I doing something wrong?
On a C++ compilator works just fine.
void setup() {
    Serial.begin(115200);
    String hexstring = "B787B7";
    int number = (int) strtol( &hexstring[1], NULL, 16);
    int r = number >> 16;
    int g = number >> 8 & 0xFF;
    int b = number & 0xFF;
    Serial.print("red is ");
    Serial.println(r);
    Serial.print("green is ");
    Serial.println(g);
    Serial.print("blue is ");
    Serial.println(b);
}
void loop() {
}
你的number应该是long类型long因为int类型是用16位编码的,不能超过32,767。 
void setup() {
    Serial.begin(115200);
    String hexstring = "B787B7";
    long number = (long) strtol( &hexstring[1], NULL, 16);
    int r = number >> 16;
    int g = number >> 8 & 0xFF;
    int b = number & 0xFF;
    Serial.print("red is ");
    Serial.println(r);
    Serial.print("green is ");
    Serial.println(g);
    Serial.print("blue is ");
    Serial.println(b);
}
void loop() {
}
When I ran your code I still was not picking up red's value. However using MAC's same code
long number = (long) strtol( &hexstring[1], NULL, 16 );
to
long number = (long) strtol( &hexstring[0], NULL, 16 );
I hope this helps someone struggling with RGB and HEX values
链接地址: http://www.djcxy.com/p/78604.html上一篇: 奇怪的C ++ Arduino串行行为
下一篇: 将HEX转换为RGB的奇怪行为
