将大十六进制字符串转换为十进制



以下十六进制值:

0x82e83f52d81253e79c4

以10为基数:

38636990646568762636740

如果我尝试将其转换为decimal:

[decimal] '0x82e83f52d81253e79c4'

得到如下结果:

Cannot convert value "0x82e83f52d81253e79c4" to type "System.Decimal". Error: "Input string was not in a correct format."

将字符串中的大十六进制值转换为decimal的好方法是什么?

使用[bigint]::Parse将十六进制字符串解析为BigInteger,然后转换为[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

这可以很容易地变成一个小的实用程序函数:

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

最新更新