题解 | #整数与IP地址间的转换#
整数与IP地址间的转换
https://www.nowcoder.com/practice/66ca0e28f90c42a196afd78cc9c496ea
#include <stdio.h> #include<stdlib.h> #include<string.h> void convers(char* sct, int t, int cnt) { int index; index = 0; while (t) { sct[(3-cnt) * 8 + index++] = t % 2 + '0'; t /= 2; } } long long fastPower(int a, int n) { if (n == 0) { return 1; } long long result = 1; long long base = a; while (n > 0) { // 如果 n 是奇数,累乘当前的 base if (n % 2 == 1) { result *= base; } // 将 base 平方,同时将 n 减半 base *= base; n /= 2; } return result; } unsigned int binachartlg(char* str) { unsigned int sum; sum=0; for(int i=0;i<32;i++){ if(str[i]=='1') sum+=fastPower(2,i); } return sum; } int* intgerToAdress(unsigned int val){ int cnt,*box; unsigned int t; t=val; cnt=0; char*cat; cat=calloc(33,sizeof(char)); while(t){ cat[cnt++]=t%2+'0'; t/=2; } cat[33]='\0'; box=calloc(4,sizeof(int)); for(int i=0;i<4;i++){ for(int j=0;j<8;j++){ if(cat[8*i+j]=='1') box[3-i]+=fastPower(2,j); } } return box; } //功能2:将整数转化成地址符 int main() {//字符串切割--》字符串转十进制--》十进制转2进制字符串 // --》2进制字符串转长整型 int cnt, temp,*p; unsigned int in_number,result; char str[16]; char* scal,*cotan; char* base[4]; scanf("%s", str); scanf("%u",&in_number); const char delimiters[] = "."; // 使用 strtok 分割字符串 char* token = strtok(str, delimiters); // 循环获取所有分割后的子字符串 cnt = 0; scal = malloc(sizeof(char)*33); cotan=malloc(sizeof(char)*33); while (token != NULL) { base[cnt] = token; temp = atoi(base[cnt]); convers(scal, temp, cnt); cnt++; // 下一次调用 strtok 时传入 NULL 继续分割 token = strtok(NULL, delimiters); } scal[33]='\0'; result =binachartlg(scal); p=intgerToAdress(in_number); printf("%u\n",result); for(int k=0;k<4;k++){ if(k==3) printf("%d",p[k]); else printf("%d.",p[k]); } }