C# convert hex into ip

时间秒杀一切 提交于 2020-01-21 12:08:16

问题


i have hex values in the format of 4a0e94ca etc, and i need to convert them into IP's, how can i do this in C# ?


回答1:


If the values represent IPv4 addresses you can use the long.Parse method and pass the result to the IPAddress constructor:

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.




回答2:


Well, take the format of an IP in this form:

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.

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.




回答3:


Check C# convert integer to hex and back again

    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));


来源:https://stackoverflow.com/questions/1355147/c-sharp-convert-hex-into-ip

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!