Welcome PowerShell User! This recipe is just one of the hundreds of useful resources contained in the Windows PowerShell Cookbook, 3rd edition.

If you own the book already, login here to get free, online, searchable access to the entire book's content.

If not, the Windows PowerShell Cookbook is available at Amazon, O'Reilly, or any of your other favourite book retailers. If you want to see what the PowerShell Cookbook has to offer, enjoy this free 90 page e-book sample: "The Windows PowerShell Interactive Shell".

You want to convert a number to a different base.

The PowerShell scripting language allows you to enter both decimal and hexadecimal numbers directly. It does not natively support other number bases, but its support for interaction with the .NET Framework enables conversion both to and from binary, octal, decimal, and hexadecimal.

To convert a hexadecimal number into its decimal
representation, prefix the number with `0x`

to enter the number as hexadecimal:

PS > $myErrorCode = 0xFE4A PS > $myErrorCode 65098

To convert a binary number into its decimal representation,
supply a base of `2`

to the `[Convert]::ToInt32()`

method:

PS > [Convert]::ToInt32("10011010010", 2) 1234

To convert an octal number into its decimal representation,
supply a base of `8`

to the `[Convert]::ToInt32()`

method:

PS > [Convert]::ToInt32("1234", 8) 668

To convert a number into its hexadecimal representation, use
either the `[Convert]`

class or
PowerShell’s format operator:

PS > ## Use the [Convert] class PS > [Convert]::ToString(1234, 16) 4d2 PS > ## Use the formatting operator PS > "{0:X4}" -f 1234 04D2

To convert a number into its binary representation, supply a
base of `2`

to the `[Convert]::ToString()`

method:

PS > [Convert]::ToString(1234, 2) 10011010010

To convert a number into its octal
representation, supply a base of `8`

to
the `[Convert]::ToString()`

method:

PS > [Convert]::ToString(1234, 8) 2322

It is most common to want to convert numbers between bases when you are dealing with numbers that represent binary combinations of data, such as the attributes of a file. For more information on how to work with binary data like this, see Work with Numbers as Binary.

Work with Numbers as Binary

This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License.