tags:

views:

117

answers:

2

Is there a function or library that can convert any (default, octal, hex, ...) integer in C given as a char[] into an unsigned long long int ?

Examples:

1
1l
1ul
42e+10
0x2aLL
01234u
...

atoi has some problems with 0x... and the suffixes u/l.

+4  A: 

strtoull is about as close as it gets. This will stop at the suffix, but since you're always producing an unsigned long long, you don't really care about the suffix anyway. I don't believe it will work with 42e+10 either -- although the value that produces is an integer, C and C++ only define the 'e' notation for floating point numbers.

Other than that, you need/want to pass 0 as the conversion base, in which case it implements the usual C convention that a leading 0 signals octal, 0x signals hexadecimal, and 1-9 signal decimal.

Jerry Coffin
Works like it should - thank you.
tur1ng
+1  A: 

You could use sscanf and check the return value to see if it did something useful, e.g.:

bool parseValue (const char *buffer, long &value)
{
if (sscanf(buffer,"%ld",&value)==1) return true;
if (sscanf(buffer,"0x%lx",&value)==1) return true;
...
return false;
}

You can easily add more kinds of formats to this list. To extend this for floating point values as well, scan the buffer in a floating point value then cast or round it to the integer value, like this:

bool parseValue (const char *buffer, long &value)
{
if (sscanf(buffer,"%ld",&value)==1) return true;
if (sscanf(buffer,"0x%lx",&value)==1) return true;
...
double d;
if (sscanf(buffer,"%lf",&d)==1) {value=d; return true;}
...
return false;
}
Patrick