Reputation: 1519
I was wondering how to manually convert an IP address to a hex value on an x86 machine. For example, the book I was reading gives the hex representation of 192.168.42.72 as:
0x482aa8c0
but never explains how the conversion works. So, how does it?
Upvotes: 1
Views: 38826
Reputation: 2478
When you convert an IP to a long integer, you take each octet in reverse order and multiply it by 256^n
where n is the zero-based reverse index of the octet
So for this ip you're doing
(72 * 256^0) + (42 * 256^1) + (168 * 256^2) + (192 * 256^3)
= 3232246344
= 0xc0a82a48
It looks like the book is doing it backwards, but you get the idea.
Upvotes: 9
Reputation: 1
$ip = "192.168.2.14"
$ar = $ip.Split('.')
$Octet1 = "{0:X2}" -f [int]$ar[0]
$Octet2 = "{0:X2}" -f [int]$ar[1]
$Octet3 = "{0:X2}" -f [int]$ar[2]
$Octet4 = "{0:X2}" -f [int]$ar[3]
$IPAddress = $Octet4 + $Octet3 + $Octet2 + $Octet1
$IPAddress
Upvotes: 0
Reputation: 3013
Sometimes you'll see it formatted like this for HEX with IP addresses.
0xC0.0xA8.0x2A.0x48
Here's how I do it in my head, because I'm not good with large numbers, since Hex is based 16. The chart below is DEC on left and HEX on right.
0 = 0
1 = 1
2 = 2
3 = 3
4 = 4
5 = 5
6 = 6
7 = 7
8 = 8
9 = 9
10 = A
11 = B
12 = C
13 = D
14 = E
15 = F
Then once you have the chart memorized, it's just basic math
192 = C0 = (192/16) = 12.0 = take the remainder (0 x 16) = 0 convert it to Hex (0)
then take the result (12) divide it by 16 (12/16) and if it's less then 1 then just
covert the remainder to hex 12 = C then add it up backwards for C0
168 = A8 = (168/16) = 10.8 = he remainder (.8 x 16) = 12.8 convert it to hex (A) then
take the result (12) divide it by 16 (12/16) and if it's less then 1 then just covert
the remainder to hex 0 = 0 then add it up backwards for 0A8 or A8
42 = 2A = (42/16) = 2.625 = The remainder (.625 x 16) = 10 convert it to hex (A) then
take the result (2) divide it by 16 (2/16) and if it's less then 1 then just covert the
remainder to hex 2 = 2 then add it up backwards for 2A
72 = 48 = Your turn
Upvotes: 2
Reputation: 7056
Don't see any powershell answers, so here goes.
This first sample converts IP address to hex.
$Octet1 = "{0:X2}" -f 192
$Octet2 = "{0:X2}" -f 168
$Octet3 = "{0:X2}" -f 42
$Octet4 = "{0:X2}" -f 72
$IPAddress = "0x"+$Octet1 + $Octet2 + $Octet3 + $Octet4
$IPAddress
Result
0xC0A82A48
and this one converts hex back to decimal IP address.
$Octet1 = "{0:D}" -f 0xC0
$Octet2 = "{0:D}" -f 0xA8
$Octet3 = "{0:D}" -f 0x2A
$Octet4 = "{0:D}" -f 0x48
$IPAddress = $Octet1 +"."+ $Octet2 +"."+ $Octet3 +"."+ $Octet4
$IPAddress
Result
192.168.42.72
Upvotes: 1
Reputation: 1
first convert 192.168.42.72 into binary number as- 11000000.10101000.00101010.01001000 then take 4-4 bits as taken in Binary to Hex number conversion.. so.. 1100 0000. 1010 1000. 0010 1010. 0100 1000 and Hex for this Ip is: C 0. A 8.2 A.4 8 now in accurate Hex representation of IP address. HEX Code Is: 0xC0A82A48.
easiest method that i know...
Upvotes: 0