How can I convert a hex ip (such as 42477f35
), and get it to spit out the correct decimal ip (in the example before, the correct result is 66.71.127.53
You could use sscanf to pick the hexadecimal out of the original string as integers and then use sprintf to put them into another string in the proper format.
sscanf(hexipstring, "%2x%2x%2x%2x", &uint0, &uint1, &uint2, &uint3);
sprintf("%u.%u.%u.%u", uint0, uint1, uint2, uint3);
Or something like that. i'm never really sure with scanf, so read through some man pages. The "%2x" should tell scanf to use 2 characters at most and interpret them as a hexadecimal number.
-edit: Caf's code is better since it checks for errors in sscanf and uses snprintf rather than sprintf. More errorproof. Use it instead of mine.
This is one possibility:
#include <stdio.h>
int ip_hex_to_dquad(const char *input, char *output, size_t outlen)
{
unsigned int a, b, c, d;
if (sscanf(input, "%2x%2x%2x%2x", &a, &b, &c, &d) != 4)
return -1;
snprintf(output, outlen, "%u.%u.%u.%u", a, b, c, d);
return 0;
}
Split the hex ip into octets (two hex digits at a time), and convert each octet to a decimal integer.