题解 | #整数与IP地址间的转换#
整数与IP地址间的转换
https://www.nowcoder.com/practice/66ca0e28f90c42a196afd78cc9c496ea
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> void rollback(char* str) { int len = strlen(str); for (int i = 0; i < len / 2; i++) { char tmp; tmp = str[i]; str[i] = str[len - i - 1]; str[len - 1 - i] = tmp; } } int main() { char str[20] = {'\0'}; int dec_ip; scanf("%s %d", str, &dec_ip); str[strlen(str)] = '.'; int duan_ip[5] = {0}; int count = 0; char* p = strtok(str, "."); while (p != NULL) { duan_ip[count++] = atoi(p); p = strtok(NULL, "."); } unsigned int dec = (duan_ip[0] << 24) + (duan_ip[1] << 16) + (duan_ip[2] << 8) + (duan_ip[3]); printf("%u\n", dec); for (int i = 0; i < 4; i++) { duan_ip[i] = (dec_ip >> ((3 - i) * 8)) & 0xff ; } printf("%d.%d.%d.%d\n", duan_ip[0], duan_ip[1], duan_ip[2], duan_ip[3]); return 0; }