Hex IP to Decimal IP conversion

后端 未结 3 1303
再見小時候
再見小時候 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.

提交回复
热议问题