Help with string to uint8_t variable

Hi, what is the correct way to assign a two-character long string to a uint8_t variable? In a way that replicates assigning it like so for example: "uint8_t p1 = 0xb3" (this works obviously) but with a string variable instead.

I so far have tried a few methods and only the current one doesn't return "cannot convert 'String' to 'const char*" errors. That code is below, however it only outputs "0", so I'm clearly missing something. Any help is appreciated, thanks!

String string1 = "b3";
void setup() {
  Serial.begin(115200);
}
void loop() {
  uint8_t p1 = atoi(string1.c_str());
  Serial.println(p1);
}

You can use https://cplusplus.com/reference/cstdlib/strtoul/ and specify that the base is 16

Or use https://cplusplus.com/reference/cstdio/sscanf with the format "%ux"

Sscanf() will bring a larger function in memory, eating up then more flash.

Appreciate the response, tried implementing your first recommendation but believe I've done so incorrectly (new code below). It's no longer outputting "0", and is now outputting "179". How should I have correctly written with strtoul? Thanks again:

String string1 = "b3";
void setup() {
  Serial.begin(115200);
}
void loop() {
  uint8_t p1 = strtoul(string1.c_str(), NULL, 16);
  Serial.println(p1);
}

Dont use the String class when there is no need to.

B3HEX is really 179 DEC. You get the right output.

If you want to see b3 printed out, use Serial.println(p1, HEX);

Oh interesting, appreciate the learning moment. So as far as my uint8_t p1 variable is concerned, is there a difference between what's being stored with my above code versus literally assigning "uint8_t p1 = 0xb3"?

If you know the value will be 0xb3 then just define the uint8_t with that value. No need to loose memory for a string and MCU time to then convert…

Perfect, thanks.

Have fun!

What you are really asking is how to convert string hex into byte

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