题解 | #整数与IP地址间的转换#
整数与IP地址间的转换
https://www.nowcoder.com/practice/66ca0e28f90c42a196afd78cc9c496ea
//HJ33 整数与IP地址间的转换 #include <stdio.h> /* //思路 涉及到两个实现,1将字符串转化成二进制同时整合成一个int 2将一个int,拆分成4个8位块,每个模块输出对应的十进制数字 */ //1:可以准确识别出4个部分的数字,将其转换为int,并且addr[0]<<24+addr[1]<<16+addr[2]<<8+addr[3]就得到整合后的 #include <string.h> #include <stdlib.h> int TransToNum(char* addr) { char address[4] = {0}; //int identify=-1; int num = 0; for (int i = 0; i < 4; i++) { sscanf(addr, "%[^.]", address); //identify+=strlen(address); addr = addr + strlen(address) + 1; num += atoi(address) << 8 * (3 - i); } return num; } //2:一个大数拆成能被2的次方们相加,列个2的次方的表一个个加,诶不对,直接利用位运算可以直接出来,每8位 char* NumToAddr(unsigned int num) { //用一个数组保存每一位数字 //char arr[4]; //用一个字符串将数组内的数字连接起来 char* addr = (char*)malloc(15 * sizeof(char)); memset(addr, 0, 15); //char *p=addr; for (int i = 0; i < 4; i++) { unsigned int numpiece = num & (0x0 | 0xFF << 8 * (3 - i)); //numpiece=numpiece>>8*(3-i); char tmp[5]; //不支持了! //itoa(numpiece>>8*(3-i),tmp,10); //用sprintf代替 sprintf(tmp, "%d.", numpiece >> 8 * (3 - i)); strcat(addr, tmp); //strcat(addr,"."); } addr[strlen(addr) - 1] = 0; return addr;//错误点1:字符串返回被抹杀,没有malloc } int main() { char addr1[15 + 1] = "10.0.3.193"; unsigned int addr2 = 167969729; scanf("%s", addr1); scanf("%d", &addr2); printf ("%u\n%s", TransToNum(addr1), NumToAddr(addr2)); }