将字符串作为十六进制转换为十六进制 [英] Convert string as hex to hexadecimal
问题描述
我有一个接受 uint64_t
变量的函数.通常我会这样做:
I have a function that takes an uint64_t
variable. Normally I would do this:
irsend.sendNEC(result.value);
result.value
是十六进制的 uint64_t(我认为).如果我这样做:
result.value
is an uint64_t as hexadecimal (I think). If I do this:
String((uint32_t) results.value, HEX)
我明白了:
FF02FD
如果我这样做:
irsend.sendNEC(0x00FF02FD)
它完美运行,正是我想要的.
it works perfectly and is what I want.
我不想获取 result.value
,而是想把它写成一个字符串(因为那是我从 GET 请求中得到的).如何将 "FF02FD"
变成 0x00FF02FD
?
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
?
也许这样更容易理解:
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:
没有匹配的函数调用'IRsend::sendNEC(String&)'
no matching function for call to 'IRsend::sendNEC(String&)'
因为:
void sendNEC(uint64_t data, uint16_t nbits = NEC_BITS, uint16_t repeat = 0);
推荐答案
评论文章:
如前所述,可以使用 C 标准库函数将包含十六进制值的字符串转换为实际整数值,例如字符串到无符号长型"(strtoul
) 或字符串到无符号long long" (strtoull
).从 Arduino 类型的 String
可以使用 c_str()
成员函数将实际的 const char*
获取到数据中.总而言之,一个十六进制字符串到整数的转换为
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()));
}
}
附录:在不同平台上使用 int
或 long
时要小心.在带有 8 位微控制器的 Arduino Uno/Nano 上,例如 ATMega328P,int
是 int16_t
.在 32 位 ESP8266 CPU 上,int
是 int32_t
.
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
.
这篇关于将字符串作为十六进制转换为十六进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!