将IP地址转换为十六进制

问题描述:

我想知道如何在x86机器上手动将IP地址转换为十六进制值。例如,这本书我读给出192.168.42.72十六进制表示为:将IP地址转换为十六进制

0x482aa8c0 

,但从来没有解释如何转换工作。那么,它是如何呢?

当您将IP为长整型,您需要按相反的顺序每个字节和256^n乘以其中ñ是这个IP你”的八位位组的从零开始的反向索引

所以重做

(72 * 256^0) + (42 * 256^1) + (168 * 256^2) + (192 * 256^3) 
= 3232246344 
= 0xc0a82a48 

看起来这本书正在倒退,但你明白了。

+0

另外值得注意的是,有函数来为你做一个家庭,[INET_ATON](http://linux.die.net/man/3/inet_aton)et al – 2012-07-20 15:10:39

+1

它不一定会倒退,这可能是由于[endianness](http://en.wikipedia.org/wiki/Endianness),它出现在另一个方向 – 2012-07-20 15:15:10

+0

@DanielDiPaolo不是整个TCP堆栈指定为big-endian?对不起,我知道这是一个陈旧的问题。 – apraetor 2016-03-07 18:02:08

有时你会看到它的格式是这样的HEX IP地址。

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成二进制数原样 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。

,我知道最简单的方法...

看不到任何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 = "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