tags:

views:

392

answers:

3

C (gcc on linux): How do i convert a hex string "0xfffffff" to an integer ?

+6  A: 
 scanf("%x", &integer);
 sscanf("0xffffffff", "%x", &integer);
EFraim
+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
+1. I doubt though that the second argument was devised solely for debugging. It seems usable for continuing the parsing to me.
EFraim
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
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
+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
+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
Feel free to update the question with your solution, and mark something that was helpful as "the answer".
Johan