sql 服务器中的无符号右移 '>>>' 运算符

unsigned right shift '>>>' Operator in sql server

如何在sql服务器中编写无符号右移运算符?表达式就像 value >>> 0

例如-5381>>>0 = 4294961915

SQL服务器不支持无符号整数,所以你的值不在INT范围内。

您可以通过以下方式获得真正的二进制解释:

SELECT CAST(-5381 AS VARBINARY)

如果您乐于在浮点运算范围内工作,您可以做:

SELECT -5381.0 + (POWER(2, 30) * 4.0)

T-SQL 没有位移运算符,因此您必须自己实现一个。这里有一个位移位的实现:http://dataeducation.com/bitmask-handling-part-4-left-shift-and-right-shift/

您必须将整数转换为 varbinary,使用位移函数并转换回整数,然后(希望如此)嘿-presto!这就是您期待的结果。

实施和测试留作 reader...

的练习

编辑——为了澄清我在下面评论中的内容,执行此 SQL 将展示各种 CAST 给出的不同结果:

SELECT -5381 AS Signed_Integer,
        cast(-5381 AS varbinary) AS Binary_Representation_of_Signed_Integer,
        cast(cast(-5381 AS bigint) AS varbinary) AS Binary_Representation_of_Signed_Big_Integer, 
        cast(cast(-5381 AS varbinary) AS bigint) AS Signed_Integer_Transposed_onto_Big_Integer, 
        cast(cast(cast(-5381 AS varbinary) AS bigint) AS varbinary) AS Binary_Representation_of_Signed_Integer_Trasposed_onto_Big_Integer

结果:

Signed_Integer Binary_Representation_of_Signed_Integer                        Binary_Representation_of_Signed_Big_Integer                    Signed_Integer_Transposed_onto_Big_Integer Binary_Representation_of_Signed_Integer_Trasposed_onto_Big_Integer
-------------- -------------------------------------------------------------- -------------------------------------------------------------- ------------------------------------------ ------------------------------------------------------------------
-5381          0xFFFFEAFB                                                     0xFFFFFFFFFFFFEAFB                                             4294961915                                 0x00000000FFFFEAFB