How to Convert Decimal to Hexadecimal in PowerShell
Introduction
Converting decimal to hexadecimal string can be a tricky process. Fortunately, PowerShell provides an easy way to convert decimal number into hexadecimal string.
In this blog post, we’ll take a look at how you can use some commands to convert decimal into hexadecimal.
Solution
Using Format Operator
In PowerShell, format operator -f
can be used to create complex strings. So, we can also use this operator to convert decimal to hexadecimal string.
'{0:x}' -f 24755
Hexadecimal string can be represented in lower-case or upper-case. To get Hex string in Upper-case, we just need to replace x
with X
.
'{0:X}' -f 24755
While the former result is 60b3
, the latter result will be 60B3
.
Using ToString method
When using ToString
method, we must specify numeric format string to achieve similar conversion. In this case, X
will represent hexadecimal format.
$dec = 24755
$hex = $dec.ToString("X")
Write-Host $hex
For result in lower-case, we just need to replace X
with x
.
$dec = 24755
$hex = $dec.ToString("x")
Write-Host $hex
Using Convert class from .NET Framework
.NET Framework classes provide powerful methods for performing various types of data conversion tasks including converting decimal number into hexadecimal string.
The most commonly used class is System.Convert
which provides several static methods that are specifically designed for converting string into different data types such as int, double, etc.
To get list of static methods that can be used for conversion, we can use following command:
[Convert] | Get-Member -Static
Later, to convert decimal to hex string, we can use following script:
$dec = 24755
$hex = [Convert]::ToString($dec, 16)
Write-Host $hex
The output of above script is 60b3
.
Using String Format from .NET Framework
Similar to previous methods, we can also use String Format from .NET Framework to achieve the conversion.
$dec = 24755
$hex = [string]::Format("{0:X}", $dec)
Write-Host $hex
For result in lower-case, we can replace X
with x
.
$dec = 24755
$hex = [string]::Format("{0:x}", $dec)
Write-Host $hex
Conclusion
Converting decimal number to hexadecimal string is incredibly easy and efficient in PowerShell, just remember we can use PowerShell operator as well as methods/functions from .NET Framework.