我想使用uint64变量将十六进制字符串(如“43a2be2a42380”)转换为十进制表示形式。我需要这个,因为我正在实现一个充当键盘的RFID阅读器,按键必须是十进制数字。
我已经看到了其他答案(convert HEX string to Decimal in arduino)并使用strtoul实现了一个解决方案,但它只适用于32位整数而且strtoull不可用。
uint64_t res = 0;
String datatosend = String("43a2be2a42380");
char charBuf[datatosend.length() + 1];
datatosend.toCharArray(charBuf, datatosend.length() + 1) ;
res = strtoul(charBuf, NULL, 16);
如何使用Arduino获取大十六进制字符串/字节数组的十进制数?
答案 0 :(得分:6)
...使用
strtoul
的解决方案,但它仅适用于32位整数,strtoull
不可用。
使用strtoul()
执行两次,对于较低的四个字节执行一次,对其余执行一次并添加两个结果,事先将后者乘以0x100000000LLU
。
答案 1 :(得分:5)
您可以自己实施:
#include <stdio.h>
#include <stdint.h>
#include <ctype.h>
uint64_t getUInt64fromHex(char const *str)
{
uint64_t accumulator = 0;
for (size_t i = 0 ; isxdigit((unsigned char)str[i]) ; ++i)
{
char c = str[i];
accumulator *= 16;
if (isdigit(c)) /* '0' .. '9'*/
accumulator += c - '0';
else if (isupper(c)) /* 'A' .. 'F'*/
accumulator += c - 'A' + 10;
else /* 'a' .. 'f'*/
accumulator += c - 'a' + 10;
}
return accumulator;
}
int main(void)
{
printf("%llu\n", (long long unsigned)getUInt64fromHex("43a2be2a42380"));
return 0;
}
答案 2 :(得分:0)
更短的转换:
void str2hex(uint8_t * dst, uint8_t * str, uint16_t len)
{
uint8_t byte;
while (len) {
byte = *str-(uint8_t)0x30;
if (byte > (uint8_t)0x9) byte -= (uint8_t)0x7;
*dst = byte << 4;
str++;
byte = *str-(uint8_t)0x30;
if (byte > (uint8_t)0x9) byte -= (uint8_t)0x7;
*dst |= byte;
str++; dst++;
len -= (uint16_t)0x1;
}
}
而不是从unsigned char buffer获取uint64_t:
uint64_t hex2_64(uint8_t * ptr)
{
uint64_t ret;
ret = (uint64_t)((uint64_t)(*ptr) << (uint64_t)56); ptr++;
ret |= (uint64_t)((uint64_t)(*ptr) << (uint64_t)48); ptr++;
ret |= (uint64_t)((uint64_t)(*ptr) << (uint64_t)40); ptr++;
ret |= (uint64_t)((uint64_t)(*ptr) << (uint64_t)32); ptr++;
ret |= (uint64_t)((uint64_t)(*ptr) << (uint64_t)24); ptr++;
ret |= (uint64_t)((uint64_t)(*ptr) << (uint64_t)16); ptr++;
ret |= (uint64_t)((uint64_t)(*ptr) << (uint64_t)8); ptr++;
ret |= (uint64_t)(*ptr);
return ret;
}