我有4a0e94ca等格式的十六进制值,我需要将它们转换为IP,我怎么能在C#中做到这一点?
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.
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.
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));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.