我需要读取计算机的ip地址,这已经完成了。之后,我需要将接收到的ip值更改为十六进制,然后更改为十进制,基本上如下所示
127.0.0.1将值反转为1.0.0.127,然后是十六进制0100007F,最后是16777343。
public static string GetLocalIPAddress()
{
var host = Dns.GetHostEntry(Dns.GetHostName());
foreach (var ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
string hexValue = ip.ToString();
string cleanAmount = hexValue.Replace(".", string.Empty);
Console.Write(cleanAmount + "\n");
return ip.ToString();
}
}
throw new Exception("No network adapters with an IPv4 address in the system!");
}
static void Main(string[] args)
{
GetLocalIPAddress();
}发布于 2018-10-01 17:51:59
这就是你要的
string input = "127.0.0.1";
string hex = string.Concat(input.Split('.').Reverse().Select(x => int.Parse(x).ToString("X").PadLeft(2,'0'))); // 0100007F
int result = Convert.ToInt32(hex, 16); //16777343发布于 2018-10-01 17:51:19
您可以使用Convert.ToString将int从十进制转换为不同的十进制:
Convert.ToString(127, 16); //16 for hexadecimal发布于 2018-10-01 17:55:00
为什么你想要逆转任何东西呢?
您只需读取每个组,并将其值乘以256^排名即可:
static void Main()
{
string ip = "127.0.0.1";
string[] splitted = ip.Split('.');
int value = 0;
int factor = 1;
for(int i=0;i<splitted.Length;i++)
{
value += factor*Convert.ToInt32(splitted[i]);
factor*=256;
}
Console.WriteLine(value);
}写16777343。
https://stackoverflow.com/questions/52588385
复制相似问题