unsigned right shift '>>>' Operator in sql

2019-05-14 00:32发布

问题:

How to write unsigned right shift operator in sql server? The expression is like value >>> 0

Here is the e.g. -5381>>>0 = 4294961915

回答1:

T-SQL has no bit-shift operators, so you'd have to implement one yourself. There's an implementation of a bitwise shifts here: http://dataeducation.com/bitmask-handling-part-4-left-shift-and-right-shift/

You'd have to cast your integer to a varbinary, use the bitwise shift function and cast back to integer and (hopefully) hey-presto! There's your result you're expecting.

Implementation and testing is left as an exercise for the reader...

Edit - To try to clarify what I have put in the comments below, executing this SQL will demonstrate the different results given by the various CASTs:

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

Results:

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


回答2:

SQL Server does not support unsigned integers, so your value doesn't fit in the range of INT.

You can get a true binary interpretation by:

SELECT CAST(-5381 AS VARBINARY)

If you're happy to work within the confines of floating point arithmetic, you could do:

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