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)
You can try using Linq to query the original string. The query can be
2
int
valueint
's into the final stringusing 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:
.
item
to int
and format as hexadecimal with 2 mandatory digitsresult
stringstring 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)));