redviper2100
redviper2100

Reputation: 265

Arduino - 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() {

}

Upvotes: 3

Views: 6495

Answers (2)

Alex Wine
Alex Wine

Reputation: 109

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

Upvotes: 10

MAC
MAC

Reputation: 429

Your number should be of type long as type int is coded on 16 bits and cannot take value above 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() {

}

Upvotes: 7

Related Questions