An IPv4 address is actually a 32-bit binary number, and then we divide it into four segments, each with 8 bits. The range that can be expressed in 8-bit binary is 0~255, so the value of each digit in dotted decimal notation is between 0~255. Sometimes, for example, in order to convert the subnet mask, we need to restore the IP address to the form of a binary string, such as: 11000000101010000000110000100001. Today I saw an example to complete this operation.
code show as below:
$ipV4 = '192.168.12.33'
-join ($ipV4.Split('.') | ForEach-Object {[System.Convert]::ToString($_,2).PadLeft(8,'0')})
#-join is to combine multiple result objects or array elements together and output.
code show as below:
11000000101010000000110000100001
We can also modify the program to show the converted form of each paragraph:
code show as below:
$ipV4.Split('.') | ForEach-Object {
'{0,5}: {1}' -f $_, [System.Convert]::ToString($_,2).PadLeft(8,'0')
}
code show as below:
192: 11000000
168: 10101000
12: 00001100
33: 00100001
Finally, let me explain the understanding of this sentence "[System.Convert]::ToString($_,2)". First, $_ represents the current loop variable. After splitting a dotted decimal IP using the Split method, each loop variable is a number, namely 192, 168, 12, and 33. And "[System.Convert]::ToString($_,2)" means to convert these numbers into binary strings. For a detailed understanding of [System.Convert]::ToString, you can parameterize the following examples:
code show as below:
#Binary
PS C:\Users\Editor> [System.Convert]::ToString(16,2);
10000
#Octal
PS C:\Users\Editor> [System.Convert]::ToString(16,8);
20
#Decimal
PS C:\Users\Editor> [System.Convert]::ToString(16,10);
16
#Hexadecimal
PS C:\Users\Editor> [System.Convert]::ToString(16,16);
10