简体   繁体   English

C#将hex转换为ip

[英]C# convert hex into ip

我有4a0e94ca等格式的十六进制值,我需要将它们转换为IP,我怎么能在C#中做到这一点?

If the values represent IPv4 addresses you can use the long.Parse method and pass the result to the IPAddress constructor : 如果值表示IPv4地址,则可以使用long.Parse方法并将结果传递给IPAddress构造函数

var ip = new IPAddress(long.Parse("4a0e94ca", NumberStyles.AllowHexSpecifier));

If they represent IPv6 addresses you should convert the hex value to a byte array and then use this IPAddress constructor overload to construct the IPAddress. 如果它们表示IPv6地址,则应将十六进制值转换为字节数组 ,然后使用此IPAddress构造函数重载来构造IPAddress。

Well, take the format of an IP in this form: 那么,采用这种形式的IP格式:

192.168.1.1

To get it into a single number, you take each part, OR it together, while shifting it to the left, 8 bits. 要将它组合成一个数字,你可以将每个部分或它们放在一起,同时将它移到左边,8位。

long l = 192 | (168 << 8) | (1 << 16) | (1 << 24);

Thus, you can reverse this process for your number. 因此,您可以针对您的号码撤消此过程。

Like so: 像这样:

int b1 = (int) (l & 0xff);
int b2 = (int) ((l >> 8) & 0xff);
int b3 = (int) ((l >> 16) & 0xff);
int b4 = (int) ((l >> 24) & 0xff);

-- Edit - 编辑

Other posters probably have 'cleaner' ways of doing it in C#, so probably use that in production code, but I do think the way I've posted is a nice way to learn the format of IPs. 其他海报可能有“更清洁”的方式在C#中使用它,所以可能在生产代码中使用它,但我认为我发布的方式是学习IP格式的好方法。

Check C# convert integer to hex and back again 检查C#将整数转换为十六进制,然后再返回

    var ip = String.Format("{0}.{1}.{2}.{3}",
    int.Parse(hexValue.Substring(0, 2), System.Globalization.NumberStyles.HexNumber),
    int.Parse(hexValue.Substring(2, 2), System.Globalization.NumberStyles.HexNumber),
    int.Parse(hexValue.Substring(4, 2), System.Globalization.NumberStyles.HexNumber),
    int.Parse(hexValue.Substring(6, 2), System.Globalization.NumberStyles.HexNumber));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM