Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arduino: Converting uint64_t to string

I have a binary that I was able to convert to a uint64_t. It's big, so I really needed a uint64_t. I'm having trouble converting it to a char array. I can do it in a standalone project but not on Arduino

Some roadblocks that I encountered:

  • I can't use sprintf ("%llu"): It's giving me a result of 0 and further googling shows that it wasn't really implemented
  • I can't use itoa: Yes, itoa was working for smaller numbers, but i'm dealing with a uint64_t and it seems like it reached its limit and giving me a negative result
  • I can't use String(123456789): I can use it for other types like int and long, but I can't pass in a uint64_t because it's not supported in the parameters
  • I can't use long long: Searching for it only gives me a variation on uint64_t (eg. use sprintf)
  • I'm having trouble using VC include in Visual Studio: When i go to my Project Properties > Configuration Properties > C/C++ > General > Additional Include Drectories and add in the path "C:\Program Files (x86)\Microsoft Visual Studio 11.0\VC\include\" Visual Studio deletes it.

Any input is greatly appreciated.

like image 301
John Avatar asked Dec 08 '22 05:12

John


2 Answers

Assuming you want to print "number" in HEX:

  uint64_t number;
  unsigned long long1 = (unsigned long)((number & 0xFFFF0000) >> 16 );
  unsigned long long2 = (unsigned long)((number & 0x0000FFFF));

  String hex = String(long1, HEX) + String(long2, HEX); // six octets
like image 60
Amir Samakar Avatar answered Dec 10 '22 17:12

Amir Samakar


Just to add onto the list of possible solutions. I use the following function:

char *uint64_to_string(uint64_t input)
{
    static char result[21] = "";
    // Clear result from any leftover digits from previous function call.
    memset(&result[0], 0, sizeof(result));
    // temp is used as a temporary result storage to prevent sprintf bugs.
    char temp[21] = "";
    char c;
    uint8_t base = 10;

    while (input) 
    {
        int num = input % base;
        input /= base;
        c = '0' + num;

        sprintf(temp, "%c%s", c, result);
        strcpy(result, temp);
    } 
    return result;
}
like image 20
Kai Chen Avatar answered Dec 10 '22 18:12

Kai Chen