Search code examples
sqlbitwise-operatorsboolean-operations

What is the Bitewise AND doing here


I have never used Bitewise AND in my life. I have researched this operator but it still eludes me as to what it exactly does. So, I will ask with some code I just came across, what is the Bitwise And doing here:

CASE
               WHEN (ft.Receiver_Status & 2) = 2 THEN '3D'
               WHEN (ft.Receiver_Status & 1) = 1 THEN '2D'
               WHEN (ft.Receiver_Status & 32) = 32 THEN 'Invalid' -- AR 220312
               ELSE 'None'

Is it enforcing the same datatype, such as smallint converts to int before comparing the value of Receiver_Status?


Solution

  • ft.Receiver_Status & 1: 1 is 20, so it is pulling out the value of the bit at position 0.

    ft.Receiver_Status & 2: 2 is 21, so it is pulling out the value of the bit at position 1.

    ft.Receiver_Status & 32: 32 is 25, so it is pulling out the value of the bit at position 5.

    Note that, for example, the = 32 in (ft.Receiver_Status & 32) = 32 is actually redundant. This could instead be (ft.Receiver_Status & 32) != 0 because all you're interested in is whether that bit is a 0 or a 1.