2

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.

Trogdor
  • 1,346
  • 9
  • 16

2 Answers2

4

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;
}
Sean
  • 60,939
  • 11
  • 97
  • 136
  • Thanks for the answer, looks like it would work (as @shuttle87's suggestion), but atoll was sufficient. I may give one of these a try for fun though – Trogdor Oct 20 '14 at 14:04
  • Why do you choose to use a const char * for the input rather than a char *? – Trogdor Oct 20 '14 at 14:06
  • 1
    @Trogdor Obviously because the function doesn't change `text`? Such pointer arguments should *always* be `const`. – unwind Oct 20 '14 at 14:21
  • @Trogdor Note that `atoll(const char *nptr)` also takes a `const`. – chux - Reinstate Monica Oct 20 '14 at 14:33
  • @unwind, obvious to those who know :). Thanks for explaining, I'm learning c as I go... – Trogdor Oct 20 '14 at 14:47
  • 2
    @Trogdor This is known as _const correctness_ and is considered good programming style. It is a form of self-documenting code, telling the reader that "rest assured that this function won't modify the stuff you pass as parameter". And it also prevents the programmer of the function from doing stupid things by accident with said parameter. – Lundin Oct 20 '14 at 15:07
1
#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);
Lundin
  • 195,001
  • 40
  • 254
  • 396