题解 | #整数与IP地址间的转换#
整数与IP地址间的转换
http://www.nowcoder.com/practice/66ca0e28f90c42a196afd78cc9c496ea
#include <stdio.h>
int main()
{
char str_ip[32] = {0};
int int_ip = 0;
int ip[4] = {0};
gets(str_ip);
scanf("%d", &int_ip);
sscanf(str_ip, "%d.%d.%d.%d", &ip[3], &ip[2], &ip[1], &ip[0]);
//注意取值范围
unsigned long str_int = ip[0]*1 + ip[1]*256 + ip[2]*256*256 + ip[3]*256*256*256;
printf("%lu\n", str_int);
int ip_str[4] = {0};
ip_str[3] |= int_ip >> 24 & 0XFF;
ip_str[2] |= int_ip >> 16 & 0XFF;
ip_str[1] |= int_ip >> 8 & 0XFF;
ip_str[0] |= int_ip & 0XFF;
char int_str[32] = {0};
sprintf(int_str, "%d.%d.%d.%d", ip_str[3], ip_str[2], ip_str[1], ip_str[0]);
printf("%s\n", int_str);
return 0;
}