【发布时间】:2012-07-20 15:02:11
【问题描述】:
我想知道如何在 x86 机器上手动将 IP 地址转换为十六进制值。例如,我正在阅读的书将 192.168.42.72 的十六进制表示为:
0x482aa8c0
但从不解释转换是如何工作的。那么,它是怎么做到的呢?
【问题讨论】:
我想知道如何在 x86 机器上手动将 IP 地址转换为十六进制值。例如,我正在阅读的书将 192.168.42.72 的十六进制表示为:
0x482aa8c0
但从不解释转换是如何工作的。那么,它是怎么做到的呢?
【问题讨论】:
当您将 IP 转换为长整数时,您将每个八位字节以相反的顺序乘以 256^n,其中 n 是八位字节的从零开始的反向索引
所以对于这个ip,你正在做
(72 * 256^0) + (42 * 256^1) + (168 * 256^2) + (192 * 256^3)
= 3232246344
= 0xc0a82a48
看起来这本书是在倒退,但你明白了。
【讨论】:
没有看到任何 powershell 答案,所以就这样吧。
第一个示例将 IP 地址转换为十六进制。
$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
结果
0xC0A82A48
这个将十六进制转换回十进制 IP 地址。
$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
结果
192.168.42.72
【讨论】:
有时您会看到带有 IP 地址的 HEX 格式如下。
0xC0.0xA8.0x2A.0x48
这就是我的想法,因为我不擅长处理大数,因为十六进制是基于 16 的。下面的图表是左边的 DEC 和右边的 HEX。
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
一旦你记住了图表,这只是基本的数学运算
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
【讨论】:
首先将 192.168.42.72 转换为二进制数 as- 11000000.10101000.00101010.01001000 然后在二进制到十六进制数字转换中取4-4位.. 所以.. 1100 0000. 1010 1000. 0010 1010. 0100 1000 此 Ip 的十六进制为:C 0. A 8.2 A.4 8 现在以精确的十六进制表示 IP 地址。 十六进制代码为:0xC0A82A48。
我知道的最简单的方法...
【讨论】:
$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
【讨论】: