我正在为测验做准备,我非常怀疑我可能会负责实现这种功能。基本上,给定一个IP地址的网络表示法,我们如何将其从32位整数转换为点分十进制表示法的字符串(类似于155.247.182.83)...?显然,我们也不能使用任何类型的inet函数...我很困惑!
最佳答案
这是一个简单的方法:(ip >> 8)
,(ip >> 16)
和(ip >> 24)
将第2、3和4个字节移到低位字节,而& 0xFF
在每一步都将最低有效字节隔离开。
void print_ip(unsigned int ip)
{
unsigned char bytes[4];
bytes[0] = ip & 0xFF;
bytes[1] = (ip >> 8) & 0xFF;
bytes[2] = (ip >> 16) & 0xFF;
bytes[3] = (ip >> 24) & 0xFF;
printf("%d.%d.%d.%d\n", bytes[3], bytes[2], bytes[1], bytes[0]);
}
第一步有一个隐含的
bytes[0] = (ip >> 0) & 0xFF;
。使用
snprintf()
将其打印为字符串。关于c - 整数到IP地址-C,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/1680365/