Convert Numbers Between Bases

1. Problem

You want to convert a number to a different base.

2. Solution

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 by 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
Tags: , , ,