Welcome PowerShell User! This recipe is just one of the hundreds of useful resources contained in the PowerShell Cookbook.

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, 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".

6.6 Convert Numbers Between Bases

Problem

You want to convert a number to a different base.

Solution

The PowerShell scripting language allows you to enter both decimal and hexadecimal numbers directly. It doesn’t 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:

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

To convert a binary number into its decimal representation, prefix it with 0b:

PS > 0b10011010010
1234

If you have the value as a string, you can 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

If you have a large array of bytes that you want to convert into its hexadecimal representation, you can use the BitConverter class:

PS > $bytes = Get-Content hello_world.txt -AsByteStream
PS > [System.BitConverter]::ToString($bytes).Replace("-","")
FFFE480065006C006C006F00200057006F0072006C006400200031000D000A00

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

Discussion

It’s most common to want to convert numbers between bases when you’re 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 Recipe 6.4.

See Also

Recipe 6.4, “Work with Numbers as Binary”