Convert string as hex to hexadecimal

人走茶凉 提交于 2019-12-12 03:28:53

问题


I have a function that takes an uint64_t variable. Normally I would do this:

irsend.sendNEC(result.value);

result.value is an uint64_t as hexadecimal (I think). If I do this:

String((uint32_t) results.value, HEX)

I get this:

FF02FD

If I do:

irsend.sendNEC(0x00FF02FD)

it works perfectly and is what I want.

Instead of grabbing the result.value, I want to write it as a string (because that's what I get from the GET request). How do I make "FF02FD" into 0x00FF02FD?

EDIT:

Maybe this makes it easier to understand:

GET: http://192.168.1.125/code=FF02FD

//Arduino grabs the FF02FD by doing:

for (int i = 0; i < server.args(); i++) {
  if (server.argName(i) == "code") {
    String code = server.arg(i);
    irsend.sendNEC(code);
  }
}

This is where I get the error:

no matching function for call to 'IRsend::sendNEC(String&)'

because:

void sendNEC(uint64_t data, uint16_t nbits = NEC_BITS, uint16_t repeat = 0);

回答1:


Comment writeup:

As already suggested, a string containing a hexadecimal value can be converted to an actual integer value using the C standard library functions such as "string to unsigned long" (strtoul) or "string to unsigned long long" (strtoull). From Arduino-type String one can get the actual const char* to the data using the c_str() member function. All in all, one does a hex-string to integer conversion as

uint64_t StrToHex(const char* str)
{
  return (uint64_t) strtoull(str, 0, 16);
}

Which can then in code be called as

for (int i = 0; i < server.args(); i++) {
  if (server.argName(i) == "code") {
    String code = server.arg(i);
    irsend.sendNEC(StrToHex(code.c_str()));
  }
}

Appendum: Be carefull about using int or long on different platforms. On a Arduino Uno/Nano with a 8-bit microcontroller, such as the ATMega328P, an int is a int16_t. On the 32-bit ESP8266 CPU, an int is int32_t.



来源:https://stackoverflow.com/questions/44683071/convert-string-as-hex-to-hexadecimal

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!