Converting to Hex

by Mar 20, 2012

Here's a simple way to convert a decimal to a hex representation, for example, if you want to display an error number in standard hexadecimal format:

PS> (-2147217407).ToString("X")
80041001

Use a lower-case "x" if you want the hex value to use lower-case letters.

PS> (212).toString('x')
d4

To convert a hex value to a decimal, prepend it with "0x":

PS> 0x8004101
134234369

As you'll see, this conversion will assume unsigned values, so values are always positive.

You can also use the -f operator:

PS> "{0:x}" -f 12345678
bc614e
PS> "{0:X}" -f 12345678
BC614E

Twitter This Tip! ReTweet this Tip!