2

#PSTip Converting numbers to HEX

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

PS> 0xAE
174

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
ae

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
00AE

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

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

2 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)
    174

    • ShayLevy says:

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

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

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

Leave a Reply

Submit Comment

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