SoFunction
Updated on 2025-03-02

PowerShell converts IP addresses into binary

The IPv4 address is actually a 32-bit binary number, and we divide it into four segments, each segment with 8 bits of digits. The range that can be expressed in 8-bit binary is 0~255, so the value of each number in dotted decimal 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: 1100000010101000000110000100001000010000100001. Today, the editor saw an example to complete this operation.

The code is as follows:

Copy the codeThe code is as follows:

$ipV4 = '192.168.12.33'
-join ($('.') | ForEach-Object {[]::ToString($_,2).PadLeft(8,'0')})
#-join is to combine multiple result objects or array elements together to output.

The results will be displayed as:
Copy the codeThe code is as follows:
11000000101010000000110000100001

We can also modify the program to display the converted form of each segment separately:

Copy the codeThe code is as follows:
$('.') | ForEach-Object {
   '{0,5} : {1}' -f $_, []::ToString($_,2).PadLeft(8,'0')
}

The results will be displayed as follows:
Copy the codeThe code is as follows:
192 : 11000000
 168 : 10101000
  12 : 00001100
  33 : 00100001
 
Finally, let me explain the understanding of this sentence "[]::ToString($_,2)". First, $_ represents the current loop variable. After breaking a dotted decimal IP using the Split method, each loop variable will be a number, that is, 192, 168, 12, 33. And "[]::ToString($_,2)" means converting these numbers into binary strings. For a detailed understanding of []::ToString, you can parameter the following examples:
Copy the codeThe code is as follows:
#Binary
PS C:\Users\Editor> []::ToString(16,2);
10000
#Octal
PS C:\Users\Editor> []::ToString(16,8);
20
#decimal
PS C:\Users\Editor> []::ToString(16,10);
16
#hexadecimal
PS C:\Users\Editor> []::ToString(16,16);
10