Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert hex string to unsigned 64bit (uint64_t) integer in a fast and safe way?

I tried

sscanf(str, "%016llX", &int64 );

but seems not safe. Is there a fast and safe way to do the type casting?

Thanks~

like image 795
Mickey Shine Avatar asked Nov 09 '10 09:11

Mickey Shine


1 Answers

Don't bother with functions in the scanf family. They're nearly impossible to use robustly. Here's a general safe use of strtoull:

char *str, *end;
unsigned long long result;
errno = 0;
result = strtoull(str, &end, 16);
if (result == 0 && end == str) {
    /* str was not a number */
} else if (result == ULLONG_MAX && errno) {
    /* the value of str does not fit in unsigned long long */
} else if (*end) {
    /* str began with a number but has junk left over at the end */
}

Note that strtoull accepts an optional 0x prefix on the string, as well as optional initial whitespace and a sign character (+ or -). If you want to reject these, you should perform a test before calling strtoull, for instance:

if (!isxdigit(str[0]) || (str[1] && !isxdigit(str[1])))

If you also wish to disallow overly long representations of numbers (leading zeros), you could check the following condition before calling strtoull:

if (str[0]=='0' && str[1])

One more thing to keep in mind is that "negative numbers" are not considered outside the range of conversion; instead, a prefix of - is treated the same as the unary negation operator in C applied to an unsigned value, so for example strtoull("-2", 0, 16) will return ULLONG_MAX-1 (without setting errno).

like image 73
R.. GitHub STOP HELPING ICE Avatar answered Oct 06 '22 20:10

R.. GitHub STOP HELPING ICE