Trogdor
Trogdor

Reputation: 1346

How to convert ascii number to uint64 in C?

I'm using Mini Ini to read data from .ini files on an embedded system. It supports reading in long integers or strings. Some of the numbers I have are too large to fit in a long, so I am reading them in as a string. However, I need to then convert them to a uint64_t.

I attempted to convert it to a float using atof and casting that to a uint64_t, which crashed and burned, presumably because casting changes how the program views the bits without changing the bits themselves.

char string_in[100];
//ret = ini_gets(section,key,"default_value",string_in,100,inifile);
//To simplify, use 
string_in = "5100200300";
uint64_t value = (uint64_t)atof(string_in);

I would appreciate help on how to convert a string to a uint64.

EDIT: Conclusion

The atoll function converts ascii to long long, which serves the purpose I needed. However, for the sake of completeness, I implemented the function provided in the accepted answer and that provided the exact answer to my question.

Upvotes: 2

Views: 2615

Answers (2)

Lundin
Lundin

Reputation: 214780

#include <stdint.h>
#include <stdlib.h>
#include <assert.h>

static_assert(sizeof(uint64_t) == sizeof(long long), 
              "Your system is mighty weird");

uint64_t u64 = strtoull(string, NULL, 10);

Upvotes: 1

Sean
Sean

Reputation: 62532

You could write your own conversion function:

uint64_t convert(const char *text)
{
    uint64_t number=0;

    for(; *text; text++)
    {
        char digit=*text-'0';           
        number=(number*10)+digit;
    }

    return number;
}

Upvotes: 4

Related Questions