Hex to value for longer hex strings

    const char-array wanted_rgb = "#11223344" // from another function

    uint32_t num = strtoul(wanted_rgb + 1, NULL, 16);
    if ( strlen(wanted_rgb) == 9 ) {
      wanted_duration = (num & 0xFF) * 1000;
      num /= 256;
    w.r = (num >> 8) & 0xFF;
    w.g = num >> 16; //green and red swapped
    w.b = num & 0xFF; // blue OK

The code above works, but I want to use longer than 9 characters, which mean that result from strtoul() is not long enough. Is there a standardized function I can use to convert just two ascii characters at a time?

Or can I still use strtoul() with longer character arrays, and it will just use the first 8 characters and ignore rest of the hex input?


You could copy a few characters into another char array then use strtoul on this new char array

Or alternatively, you could use sscanf

Here is an example of sscanf : hLzquy - Online C++ Compiler & Debugging Tool - Ideone.com

Have you tried long long and strtoull?

Thanks! I sort of tried strtoull(), meaning that I typed the word, but it didn’t go orange in the IDE, so I thought it was not available. It is, and it works.

Related Q: To remove a byte, I divide by 256. Would it be better that I did some bitshifting instead?

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.