C # convert hex to ip

I have hexadecimal values ​​in 4a0e94ca format, etc. and I need to convert them to IP addresses, how can I do this in C #?

+3
source share
3 answers

If the values ​​represent IPv4 addresses, you can use the method long.Parseand pass the result to the IPAddress Constructor :

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

If they represent IPv6 addresses, you must convert the hexadecimal value to an array of bytes , and then use this constructor of the IPAddress constructor to create the IPAddress.

+12
source

Well, take the IP format in this form:

192.168.1.1

, , , 8 .

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

, .

:

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

-

, , " " #, , , , , , , - IP-.

+3

#

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

Source: https://habr.com/ru/post/1716450/


All Articles