0

I do not have access to anything like strtoull on my actual platform, so I need to find/handroll one. I've tried all four from this answer and they all give me the same, wrong answer, on my windows testing platform. I also tried on online compilers.

One of the functions is

unsigned long long strtoull_simple(const char *s) {
  unsigned long long sum = 0;
  while (*s) {
    sum = sum*10 + (*s++ - '0');
  }
  return sum;
}

And given "87ddb08343547aec" it produces 9277008343552481 instead of the real value 9790175242790140652 evident here and also evident if you use strtoull where available. Why do all of those functions fail to provide the correct value?

ony_pox232
  • 171
  • 1
  • 10

1 Answers1

2

As mentioned in the comments, the code looks like it is for base-10 numbers but the number you are trying to parse looks base-16. You can add a parameter to specify the base:

unsigned long long strtoull_simple(const char *s, int base)
{
    unsigned long res = 0;
    while (*s) {
        // TODO: handle invalid chars
        char c = tolower(*s);
        res = (res * base) + (isdigit(c) ? c - '0' : c - 'a' + 10);
        *s++
    }
    return res;
}

And call it with

printf("%llu", strtoull_simple("87ddb08343547aec", 16));

Output:

9790175242790140652
001
  • 13,291
  • 5
  • 35
  • 66
  • Great, just did something almost exactly like that. Can I ask why not use `unsigned char c`? I'm really hung up on chars and them having to be unsigned when it comes to reading hex.. Is this true? – ony_pox232 Aug 19 '20 at 21:01
  • Since it is dealing with single digits, there are no worries about overflowing the `char`. So `signed` or `unsigned` work. Also, `char` may be `unsigned` by default: [Is char signed or unsigned by default?](https://stackoverflow.com/a/2054941) – 001 Aug 19 '20 at 21:06
  • 1
    Side note: `strtoull` will stop parsing when it finds an invalid character. This needs a bit more checking to replicate that behaviour. Smurf and I'm too blind to see the comment pointing out exactly that. – user4581301 Aug 19 '20 at 21:14
  • `Smurf and I'm too blind to see the comment pointing out exactly that` .. say.. what? – ony_pox232 Aug 19 '20 at 22:32