3 回答
TA贡献1798条经验 获得超3个赞
实际上,我不认为乘法是最明确的方式(完全正确)。
Int32“格式化”的IP地址可以看作以下结构
[StructLayout(LayoutKind.Sequential, Pack = 1)]
struct IPv4Address
{
public Byte A;
public Byte B;
public Byte C;
public Byte D;
}
// to actually cast it from or to an int32 I think you
// need to reverse the fields due to little endian
所以要转换IP地址64.233.187.99你可以这样做:
(64 = 0x40) << 24 == 0x40000000
(233 = 0xE9) << 16 == 0x00E90000
(187 = 0xBB) << 8 == 0x0000BB00
(99 = 0x63) == 0x00000063
---------- =|
0x40E9BB63
所以你可以使用+添加它们,或者你可以将它们组合在一起。结果是0x40E9BB63,这是1089059683.(在我看来,以十六进制看,它更容易看到字节)
所以你可以把函数写成:
int ipToInt(int first, int second,
int third, int fourth)
{
return (first << 24) | (second << 16) | (third << 8) | (fourth);
}
- 3 回答
- 0 关注
- 563 浏览
添加回答
举报