简体   繁体   中英

C# ip to hex to decimal

I need to read computers ip adress, which is already done. After that I need to change the recieved ip value to hex and then to decimal, basically like this

127.0.0.1 flip the value to 1.0.0.127 to hex 0100007F and finally to 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();
    }

Here you go

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

您可以使用Convert.ToStringint从十进制转换为其他数字系统:

Convert.ToString(127, 16); //16 for hexadecimal

Why do you want to reverse anything at all?
You could just read each group and multiply its value by 256^rank:

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

Writes 16777343 .

Try this:

string ipAddress = "127.0.0.1";
string[] parts = ipAddress.Split('.');
string hexResult = "";
// loop backwards, to reverese order of parts of IP
for (int i = parts.Length - 1; i >= 0; i--)
    hexResult += int.Parse(parts[i]).ToString("X").PadLeft(2, '0');
int finalResult = Convert.ToInt32(hexResult, 16);

It depends why you want this reversed, and if this is an endian issue

essentially you just need to return your int

BitConverter.ToInt64(IPAddress.Parse("127.0.0.1").GetAddressBytes(), 0);

Or a more verbose example

var bytes = IPAddress.Parse("127.0.0.1").GetAddressBytes();

if (!BitConverter.IsLittleEndian)
   Array.Reverse(bytes);

for (int i = 0; i < bytes.Length; i++)
    Console.Write(bytes[i].ToString("X2"));

Console.WriteLine("");

long r = BitConverter.ToInt32(bytes, 0);
Console.WriteLine(r);

Output

7F000001 
16777343

Full Demo Here

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM