C (gcc on linux): How do i convert a hex string "0xfffffff" to an integer ?
views:
392answers:
3
+6
A:
The other, quasi-portable, way is strtol
and it's fellows strtoul
, strtoll
, and strtoull
. They look like:
long
strtol(const char * restrict nptr, char ** restrict endptr, int base);
Use is a little strange. The first argument is the string you want to convert, and the third is the base, which for hex would be 16. The second argument is used for debugging: it can point to the first character in the hex string which failed to convert.
quark
2009-07-31 07:06:38
+1. I doubt though that the second argument was devised solely for debugging. It seems usable for continuing the parsing to me.
EFraim
2009-07-31 07:14:50
Ah! So you can use it as part of general tokenizing. I hadn't thought of that. (All the situations where I've used it had a more general tokenizer, and used `strtol` to get a value of a string known to be an integer... so I always passed `NULL` to `endptr`.)
quark
2009-07-31 07:19:28
And checking for errors. If zero is returned you should need to distinguish between a successful parse of zero and a failed parse. Also the base can be left as 0 if a leading '0x' is required. A base of 0 will parse decimal, octal and hexadecimal numbers based on their prefix.
Charles Bailey
2009-07-31 07:20:56
+1 Charles. That's the reason. It's the inverse of an idiom more common these days which would pass the return value back in an out parameter, and use the return value for the error code.
quark
2009-07-31 07:24:43
+1
A:
Ok. strtol does it.
int main()
{
char s[] = "0xf0f0";
unsigned int x=0;
x = strtol(s, NULL, 16);
printf("s = %s and x = %u\n", s, x);
}
Cheezo
2009-07-31 07:07:55
Feel free to update the question with your solution, and mark something that was helpful as "the answer".
Johan
2009-07-31 07:15:05