要求:也就提取出IP地址即char buf0[]=”192.168.0.253″中的数字“1921680253”保存在char buf1[]中,再转为C0A800FD,以16进制保存在char buf2[]中
printf(“\n%x”,buf2); 输出结果:C0A800FD
printf(“\n%x”,buf2); 输出结果:C0A800FD
解决方案
15
#include <stdlib.h> void split_ip_address(char* address,int* output) { char* s=(char*)address; char* ss=nullptr; int n=0; while (n<4&&(ss=strchr(s,"."))!=nullptr) { *ss=0; output[n++]=atoi(s); s=ss+1; } if (n<4&&*s) output[n]=atoi(s); } int main() { char buf0[]="192.168.0.253"; int a[4]; split_ip_address(buf0,a); char buf1[16],buf2[16]; sprintf_s(buf1,"%d%d%d%d",a[0],a[1],a[2],a[3]); sprintf_s(buf2,"%02X%02X%02X%02X",a[0],a[1],a[2],a[3]); printf("buf1=%s\n",buf1); printf("buf2=%s\n",buf2); return 0; }
5
inet_pton+ntohl+snprintf
20
//提取出IP地址即char buf0[]="192.168.0.253"中的数字“192168000253”保存在char buf1[]中,再转为C0A800FD,以16进制保存在char buf2[]中 //printf("%s",buf2); 输出结果:C0A800FD #include <stdio.h> char buf0[]="192.168.0.253"; char buf1[13]; char buf2[9]; int v[4]; int main() { sscanf(buf0,"%d.%d.%d.%d",&v[0],&v[1],&v[2],&v[3]); sprintf(buf1,"%03d%03d%03d%03d",v[0],v[1],v[2],v[3]); printf("buf1:[%s]\n",buf1); sprintf(buf2,"%02X%02X%02X%02X",v[0],v[1],v[2],v[3]); printf("buf2:[%s]\n",buf2); return 0; } //buf1:[192168000253] //buf2:[C0A800FD] //