首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C# ip到十六进制到十进制

问C# ip到十六进制到十进制
EN

Stack Overflow用户
提问于 2018-10-01 17:44:49
回答 5查看 761关注 0票数 0

我需要读取计算机的ip地址,这已经完成了。之后,我需要将接收到的ip值更改为十六进制,然后更改为十进制,基本上如下所示

127.0.0.1将值反转为1.0.0.127,然后是十六进制0100007F,最后是16777343。

代码语言:javascript
复制
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();
    }
EN

回答 5

Stack Overflow用户

发布于 2018-10-01 17:51:59

这就是你要的

代码语言:javascript
复制
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
票数 4
EN

Stack Overflow用户

发布于 2018-10-01 17:51:19

您可以使用Convert.ToString将int从十进制转换为不同的十进制:

代码语言:javascript
复制
Convert.ToString(127, 16); //16 for hexadecimal
票数 0
EN

Stack Overflow用户

发布于 2018-10-01 17:55:00

为什么你想要逆转任何东西呢?

您只需读取每个组,并将其值乘以256^排名即可:

代码语言:javascript
复制
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。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52588385

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档