Search code examples
c#parsingtype-conversionformathex

convertion of hexadecimal into ipaddress in c#


I need a logic how to convert hexadecimal to IP(IPV4) address for example

6F6F6F6F(HEXADECIMAL) - 111.111.111.111(IPADDRESS)
FFFFFFFF(HEXADECIMAL) - 255.255.255.255(IPADDRESS)

Solution

  • You can try using Linq to query the original string. The query can be

    1. Split original string into chunks of size 2
    2. Convert each chunk into int value
    3. Join all these int's into the final string
    using System.Linq;
    
    ...
    
    string source = "6F6F6F6F";
    
    string address = string.Join(".", source
      .Chunk(2)
      .Select(chunk => Convert.ToInt32(new string(chunk), 16)));
    

    Demo:

    using System.Linq;
    
    ...
    
    static string MyConvert(string source) => string.Join(".", source
      .Chunk(2)
      .Select(chunk => Convert.ToInt32(new string(chunk), 16)));
    
    string[] tests = {
      "6F6F6F6F",
      "FFFFFFFF",
    };
    
    string result = string.Join(Environment.NewLine, tests
      .Select(test => $"{test}(HEXADECIMAL) - {MyConvert(test)}(IPADDRESS)"));
    
    Console.Write(result);
    

    Outcome:

    6F6F6F6F(HEXADECIMAL) - 111.111.111.111(IPADDRESS)
    FFFFFFFF(HEXADECIMAL) - 255.255.255.255(IPADDRESS)
    

    Edit: Reverse can be Linq based as well:

    1. We split the source by .
    2. Parse each item to int and format as hexadecimal with 2 mandatory digits
    3. Concat all these chunks into the result string
    string source = "123.45.67.221";
    
    string result = string.Concat(source
      .Split('.')
      .Select(item => int.Parse(item).ToString("X2")));
    

    Edit 2: You can use GroupBy instead of Chunk in case of old .net versions:

    string address = string.Join(".", source
      .Select((item, index) => new { item = item, group = index / 2 })
      .GroupBy(pair => pair.group, pair => pair.item)
      .Select(group => Convert.ToInt32(new string(group.ToArray()), 16)));
    

    Fiddle