Hex IP to Decimal IP conversion

后端 未结 3 1293
再見小時候
再見小時候 2021-01-26 05:53

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

相关标签:
3条回答
  • 2021-01-26 06:06

    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.

    0 讨论(0)
  • 2021-01-26 06:29

    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;
    }
    
    0 讨论(0)
  • 2021-01-26 06:29

    Split the hex ip into octets (two hex digits at a time), and convert each octet to a decimal integer.

    0 讨论(0)
提交回复
热议问题