SELECT CONVERT(BIT, 7 & 4)

Alen Cappelletti 686 Reputation points
2021-04-03T21:29:25.75+00:00

Hi...
I saw this piece of code... and it's a new kind form me in t-sql.
Can someone explain me the meaning?

I try with:
SELECT CONVERT(BIT, 1 & 4) result (= 0)
SELECT CONVERT(BIT, 2 & 4) result (= 0)
SELECT CONVERT(BIT, 3 & 4) result (= 0)
SELECT CONVERT(BIT, 4 & 4) result (= 1)
SELECT CONVERT(BIT, 5 & 4) result (= 1)
SELECT CONVERT(BIT, 6 & 4) result (= 1)
SELECT CONVERT(BIT, 7 & 4) result (= 1)
SELECT CONVERT(BIT, 8 & 4) result (= 0)

If I wrote right
Thanks ALEN.

No comments
{count} votes

Accepted answer
  1. Erland Sommarskog 68,106 Reputation points Microsoft MVP
    2021-04-03T22:09:37.423+00:00

    & is bitwise AND. So if we take 5 & 4, that is 0101 & 0100 binary. The result of this is 0100, since it is only in one position there are 1 in both numbers. Then 4 is converted to bit, and when integers are converted to bit, everything that is <> 0 becomes 1.


1 additional answer

Sort by: Most helpful
  1. Monalv-MSFT 5,686 Reputation points
    2021-04-05T08:36:11.387+00:00

    Hi @Alen Cappelletti ,

    I am glad to hear that you have accepted the answer.

    Hope the following link will be helpful:
    & (Bitwise AND) (Transact-SQL)
    The & bitwise operator performs a bitwise logical AND between the two expressions, taking each corresponding bit for both expressions. The bits in the result are set to 1 if and only if both bits (for the current bit being resolved) in the input expressions have a value of 1; otherwise, the bit in the result is set to 0.

    Please do not hesitate to contact us if you have any new issues.

    Best regards
    Mona

    ----------

    If the answer is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    No comments