Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arduino: Convert hex string to uint64 or decimal string

I want to convert a hex string such as "43a2be2a42380" to their decimal representation using a uint64 variable. I need that because i'm implementing a RFID reader acting as a keyboard and the keypresses need to be the decimal digit.

I have seen other answers (convert HEX string to Decimal in arduino) and implementing a solution using strtoul but it only works for 32 bit integers and strtoull is not available.

uint64_t res = 0;
String datatosend = String("43a2be2a42380");
char charBuf[datatosend.length() + 1];
datatosend.toCharArray(charBuf, datatosend.length() + 1) ;
res = strtoul(charBuf, NULL, 16);

What can i do to get the decimal number of a big hex string / byte array using an Arduino?

like image 758
h3ct0r Avatar asked Oct 30 '25 04:10

h3ct0r


1 Answers

You can make your own implementation :

#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;
}
like image 61
Boiethios Avatar answered Nov 01 '25 18:11

Boiethios



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!