3

# #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 {
}

# 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

```
Filed in: Columns, Tips and Tricks Tags: , ,

### 3 Responses to "#PSTip Converting numbers to binary and back"

1. Ramakrishnan C says:

Very Nice post. Thanks. Could you please also let me know how to convert to Hex, Oct back?

• Jeremy Hagan says:

Change the ,2 to ,8 or ,16. This changes the base.