#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 

About the author: Shay Levy

Shay Levy is a Co-founder and editor of the PowerShell Magazine. He is a multiple-year recipient of the Microsoft MVP award, and a Microsoft Certified Trainer (MCT). Shay often covers PowerShell related topics on his blog and you can also follow him on Twitter at @ShayLevy

Related Posts

%d bloggers like this: