Strange behavior converting HEX to RGB

Hey guys,

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 red = number >> 16;
    int g = number >> 8 & 0xFF;
    int b = number & 0xFF;
    Serial.print("red is ");
    Serial.println(red);
    Serial.print("green is ");
    Serial.println(g);
    Serial.print("blue is ");
    Serial.println(b);

}

void loop() {
  
}
    int number = (int) strtol( &hexstring[1], NULL, 16);
    int red = number >> 16;
    int g = number >> 8 & 0xFF;
    int b = number & 0xFF;

number is an int, it has 16 bits. You are trying to stuff 24 bits into it. Yeah, 8 bits aren't going to fit.

int red = number >> 16;

What happens when you shift a 16 bit int by 16 bits? You shift every single bit off the number and are left with 0.

If by that last statement you mean it worked on your computer, well your computer probably uses 32 bit ints.

You're right! Thank you!

int number = (int) strtol( &hexstring[1], NULL, 16);

strtol() expects a NULL terminated array of chars, NOT a String address. That this appears to work at all is a miracle.

Either use toCharArray() to extract the string from the String, or shitcan the String class altogether. There is NOTHING that String can do that can't be done with strings.