#PSTip Converting numbers to binary and back

To convert a number to its equivalent binary string representation, use the Convert.ToString method with a base of 2.

PS> [Convert]::ToString(192,2)
11000000

To convert a binary number into its decimal representation, use the Convert.ToInt32 method with a base of 2 :

PS> [Convert]::ToInt32('11000000',2)
192

Binary conversions are usually used in IP addressing and subnetting calculations. Here’s an example of converting an IP address to its binary representation and back.

$ip = '192.168.10.1'

# convert to binary form
$bin = $ip -split '\.' | ForEach-Object {
    [System.Convert]::ToString($_,2).PadLeft(8,'0')
}

# print result
$bin
11000000
10101000
00001010
00000001

# join the objects
$bin -join '.'
11000000.10101000.00001010.00000001

# convert the result back to decimal
$dec = $bin | ForEach-Object {
    [System.Convert]::ToByte($_,2)
}

# print result
$dec
192
168
10
1

# join the result to form a valid IP Address
$dec -join '.'
192.168.10.1
Share on: