#PSTip Converting numbers to HEX

PowerShell can convert Hexadecimal numbers on the command line, just prefix the value with ‘0x’:

PS> 0xAE

Converting a number to HEX requires the use of .NET string formatting. Here we use the ‘x’ format specifier, it converts a number to a string of hexadecimal digits and the result is a hexadecimal string :

PS> '{0:x}' -f 174

The result is a HEX value in lower case. You can have the result in upper case by using ‘X’ instead, and also have a specific number of digits in the result by using a precision specifier. If required, the number is padded with zeros to its left to produce the number of digits given by the precision specifier.

PS> '{0:X4}' -f 174

See this page for more information on .NET Numeric Format Strings 

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

3 Responses to "#PSTip Converting numbers to HEX"

  1. goyuix says:

    For the curious reader, you can round trip that hex string back to a number through the Parse method on the int class:

    PS> [Int]::Parse(“00AE”, [System.Globalization.NumberStyles]::HexNumber)

    • ShayLevy says:

      Excellent. And as always, there are more ways to get the same result:

      PS> [System.Convert]::ToString(174,16)

      PS> [System.Convert]::ToInt32(‘ae’,16)

  2. Matt GP says:

    There is also forcing format on a number:

    PS> “{0:x2}” -f 255

    Produces a 2 digit hex of ff (255)

    the “2” in the above example can be modified if additional digits of precision are needed, for example:

    PS> “{0:x8}” -f 4096
    produces an 8 digit hex of 00001000

Leave a Reply

Submit Comment

© 2015 PowerShell Magazine. All rights reserved. XHTML / CSS Valid.
Proudly designed by Theme Junkie.
%d bloggers like this: