0

Basically I am trying to convert hex strings into unsigned long long values using strtoull. Here's the simple code

#include <stdio.h>
#include <string.h>


int main ()
{
    unsigned long long val =0;

    //printf("sizeof(unsigned long long)=%d\n", sizeof(unsigned long long));

    val = strtoull("0x8004298c42ULL",NULL,16);

    printf("%llx\n", val);

    if ( val == 0x8004298c42ULL)
    {
        printf("Success\n");
    }
    return 0;
}

I expect val to print 8004298c42 but it prints 4298c42. The 8 is being chopped off. I tried without the 0x and without the ULL too. But still the same result. Just to make sure that I am not missing out on some trivial printf format specifier thing, I even checked the contents of val. Still no use( ie Success was not printed )

I think I am missing out something trivial but don't know what!

Pavan Manjunath
  • 27,404
  • 12
  • 99
  • 125
  • The code at ideone (now) uses `` instead of ``. – Jonathan Leffler Nov 29 '14 at 01:01
  • @JonathanLeffler I changed the file at ideone after your answer. Now that your answer is there, I shall remove the link. – Pavan Manjunath Nov 29 '14 at 01:02
  • please read the link: which among other things states: Since strtoul() can legitimately return 0 or ULONG_MAX (ULLONG_MAX for strtoull()) on both success and failure, the calling program should set errno to 0 before the call, and then determine if an error occurred by checking whether errno has a nonzero value after the call. – user3629249 Nov 29 '14 at 06:57

1 Answers1

6

The function strtoull() is declared in <stdlib.h>, not <string.h>, so the compiler thinks it returns an int, not an unsigned long long.

Cure: make sure that all functions are declared before they are used. If you use gcc, then you should consider some combination of -Wall, -Wextra, -Wstrict-prototypes, -Wmissing-prototypes, -Wold-style-declaration, -Wold-style-definition and -Werror.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278