【问题标题】:Why is this PowerShell bit manipulation producing different output than Python?为什么这种 PowerShell 位操作会产生与 Python 不同的输出?
【发布时间】:2017-02-01 00:24:43
【问题描述】:

我有一个 Python 和 PowerShell 脚本,打算做同样的事情。当我在两个脚本中执行“非”运算符,然后 -1 % 256 操作时,我得到不同的输出:

PowerShell

-bnot 0: -1
(-1 % 256): -1

Python

(~0): -1
(-1 % 256): 255

而且,在不同的系统上,我再次从 PowerShell 获得不同的输出:

PowerShell

-bnot 0:  18446744073709551615
18446744073709551615 % 256: 255

Python

-bnot 0: -1
(-1 % 256): 255

如何让我的 PowerShell -bnot% 运算符每次都产生与 Python 脚本相同的输出? PowerShell 版本相同。

【问题讨论】:

  • 明确强制数字类型?在第二个例子中,你得到一个无符号整数。
  • 你知道 Python 用的是什么吗?以及我将如何在 PowerShell 中强制执行此操作?
  • 我周围没有窗户,但我想像-bnot [int]0 这样的东西应该可以。
  • 不,我认为这不起作用。
  • 实际上是 PowerShell v2.0 或更高版本?什么操作系统,哪个 PowerShell 主机(控制台或 ISE 或其他?) 什么 Python 版本?没有配置文件的 PowerShell?这两个系统有什么不同?你实际上是在做如图所示的测试,还是在使用变量?如果是这样,PowerShell 中的 $x.GetType() 和 Python 中的 type(x),它们是什么?

标签: powershell bit-manipulation powershell-2.0 bit twos-complement


【解决方案1】:

事实证明,正确的答案是 PowerShell 不像其他语言那样处理带负数的模数。

How to get PowerShell to perform modulus on negative numbers correctly.

【讨论】:

    【解决方案2】:

    第一个例子的解释是,在 PowerShell(与 .NET 上的大多数其他语言实现一样)%remainder 运算符,而不是 modulus 运算符.埃里克·利珀特explains the difference in this article.

    在第二个示例中,您似乎将二进制 NOT 运算符应用于无符号 64 位整数。一个无符号整数显然不能是负数,所以你看到的正确的是应用 NOT 到 0x0 的整数表示:

    PS C:\> -bnot [int]0
    -1
    PS C:\> -bnot [uint64]0
    18446744073709551615
    
    PS C:\> ([int]0).ToString('X2').PadLeft(8,'0')
    00000000
    PS C:\> ([int]-1).ToString('X2').PadLeft(8,'0')
    FFFFFFFF
    PS C:\> ([uint64]0).ToString('X2').PadLeft(16,'0')
    0000000000000000
    PS C:\> ([uint64]18446744073709551615).ToString('X2').PadLeft(16,'0')
    FFFFFFFFFFFFFFFF
    

    对于模运算,你可以添加除数,直到被除数大于或等于0:

    $i = -1
    $d = 256
    while($i -lt 0){
        $i += $d
    }
    $i % 256
    

    在模运算的大多数实际应用中,将除数相加一次就足够了:

    $r = ($i + $d) % $d
    

    【讨论】:

      猜你喜欢
      • 2020-02-09
      • 2021-10-07
      • 1970-01-01
      • 2022-12-05
      • 1970-01-01
      • 2023-04-11
      • 2013-03-10
      • 1970-01-01
      • 2021-11-16
      相关资源
      最近更新 更多