Use Hex Number Returned by Webhook

I have a webhook set up to return an energy level in kWh. That value is, unfortunately, a hexadecimal number like the following:

{
"InstantaneousDemand": {
"Demand": "0x00020b"
}

I am able to parse it using response templates but I can figure out how to convert it back to a decimal number. Any hints?

You can use the C function strtol().

char* input = "0x00020b";
int answer = strtol(input, NULL, 0);
Serial.printlnf("result is: %d", answer); // prints "result is: 523"

You can pass 0 or 16 for the last parameter to strtol(); with a 0, it auto-detects the numeric base using the prefix (“0x” in your case). If your string doesn’t have the “0x” prefix, then you must pass 16 if it is to be interpreted as hex.

1 Like

Awesome that worked perfect thank you! Part of my problem was i was using Particle.publish() to try to check the values. Looks like it can handle Hex numbers.

Quick follow up question (sorry pretty new to this). When the value is “0xfffffebf” which should be a negative number I am getting a really large number like 2147483647. I am not really sure why.

strtol() doesn’t “know” that you want that number interpreted as a negative number, so it sees that number as larger than int max, and returns the INT_MAX value of 2147483647.

If you need to have some of the hex strings interpreted as negative numbers, you can use strtoul() instead.