The following hexadecimal value:
0x82e83f52d81253e79c4
is the following in base 10:
38636990646568762636740
If I try to convert it to a decimal
:
[decimal] '0x82e83f52d81253e79c4'
I get the following:
Cannot convert value "0x82e83f52d81253e79c4" to type "System.Decimal". Error: "Input string was not in a correct format."
What's a good way to convert that large hexadecimal value in a string to a decimal
?
CodePudding user response:
Use [bigint]::Parse
to parse the hexadecimal string as a BigInteger
, then cast to [decimal]
:
# define hex string
$string = '0x82e83f52d81253e79c4'
# remove 0x prefix
$string = $string -replace '^0x'
# prepend `0` to avoid having [bigint]::Parse interpret number as signed
$string = "0${string}"
# now parse it as a [bigint]
$bigint = [bigint]::Parse($string, [System.Globalization.NumberStyles]::AllowHexSpecifier)
# finally cast to `[decimal]`
[decimal]$bigint
This can easily be turned into a small utility function:
function ConvertFrom-Hexadecimal
{
param(
[Parameter(Mandatory)]
[string]$Hexadecimal
)
$string = '0{0}' -f ($Hexadecimal -replace '^0x')
return [decimal][bigint]::Parse($string, [System.Globalization.NumberStyles]::AllowHexSpecifier)
}
PS ~> $decimal = ConvertFrom-Hexadecimal '0x82e83f52d81253e79c4'
PS ~> $decimal -is [decimal]
True
PS ~> $decimal
38636990646568762636740