Powershell bigint 输出与声明值不同

Powershell bigint output differ from declared value

我正在将 lesspass 密码管理器移植到 powershell,但是我在实施 _consume_entropy() method 时遇到了问题,尤其是 Python divmod.

转载

PS> [bigint]$EntropyAsInt = 99600400399777174105034830393873797761817714609490038944205586760025858632478
PS> Write-Host $EntropyAsInt
99600400399777173995117538344184441997741701018199539534149245151907290284032

差异

99600400399777174105034830393873797761817714609490038944205586760025858632478
99600400399777173995117538344184441997741701018199539534149245151907290284032
                ^ start diverging he

问题

这是怎么回事?我用错类型了吗?

我可以复制该行为,但无法解释。我可以 做的是为您提供解决方法。将变量定义为 [bigint],然后将您的号码解析为引用先前创建的变量的字符串。

[bigint]$EntropyAsInt=0
[bigint]::TryParse('99600400399777174105034830393873797761817714609490038944205586760025858632478',[ref]$EntropyAsInt)

然后您可以验证 $EntropyAsInt 是否包含您之前指定的号码。

感谢 Joel 在 Powershell slack 上的表现:

The issue is that the bigint cast doesn't take effect until after the value is parsed. It will first be parsed as a double, which in where the imprecision occurs

If you want it to retain the exact number, you need to put your literal in quotes to make it a string and have the cast itself do the parsing

[bigint]$var = "12345342827266162738883736363"

工作正常

[bigint]$EntropyAsInt = "99600400399777174105034830393873797761817714609490038944205586760025858632478"

99600400399777174105034830393873797761817714609490038944205586760025858632478[Double]...

PS> 99600400399777174105034830393873797761817714609490038944205586760025858632478
9.96004003997772E+76
PS> (99600400399777174105034830393873797761817714609490038944205586760025858632478).ToString("F0")
99600400399777200000000000000000000000000000000000000000000000000000000000000
PS> (99600400399777174105034830393873797761817714609490038944205586760025858632478).GetType()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Double                                   System.ValueType

当它转换为 [BigInt] 时,原始值已经丢失。以 [String] 开头会保留它,但是...

PS> [bigint]$EntropyAsInt = '99600400399777174105034830393873797761817714609490038944205586760025858632478'
PS> $EntropyAsInt
99600400399777174105034830393873797761817714609490038944205586760025858632478

有关详细信息,请参阅 Instantiating a BigInteger Object