如何使用 mySQL 对负数进行位移以获得 Java、Python 等结果?

How to bitshift negative numbers with mySQL to get results like in Java, Python etc?

当我想位移 -2 >> 4 时,它应该给我 -1。 python 和 java 确实给了我 -1。但是,如果我在我的 mySQL 服务器上尝试它,我会得到 1152921504606846975。我试图反转这些位来转换它等,但我无法得到 -1。那么有人知道如何对其进行位移以获得-1吗?

>>:

Shifts a longlong (BIGINT) number to the right.

The result is an unsigned 64-bit integer. The value is truncated to 64 bits. In particular, if the shift count is greater or equal to the width of an unsigned 64-bit number, the result is zero.

-1不属于无符号整数范围

根据documentation,MySQL的位移运算符生成一个无符号 64位整数。因此,如果您想获得负数的预期行为,您可以添加自己的逻辑:

WITH yourTable AS (
    SELECT 4 AS val UNION ALL
    SELECT -4
)

SELECT
    IF(val > 0, val >> 2, -1.0*((-1.0*val) >> 2)) AS result
FROM yourTable;

这输出:

1
-1.0