将字符串转换为十六进制为十六进制 [英] 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
?
也许这使它更容易理解:
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:
没有匹配函数可调用'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
)或字符串到无符号长整数长整数"(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屋!