簡體   English   中英

Arduino:將十六進制字符串轉換為uint64或十進制字符串

[英]Arduino: Convert hex string to uint64 or decimal string

我想使用uint64變量將十六進制字符串(如“43a2be2a42380”)轉換為十進制表示形式。 我需要這個,因為我正在實現一個充當鍵盤的RFID閱讀器,按鍵必須是十進制數字。

我已經看到了其他答案( HEduino中將HEX字符串轉換為Decimal )並使用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獲取大十六進制字符串/字節數組的十進制數?

...使用strtoul解決方案,但它只適用於32位整數,並且strtoull不可用。

使用strtoul()執行兩次,對於較低的四個字節執行一次,對其余執行一次並添加兩個結果,事先將后者乘以0x100000000LLU

你可以自己實現:

#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;
}

更短的轉換:

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緩沖區獲取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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM