question

acappelletti avatar image
0 Votes"
acappelletti asked Monalv-msft answered

SELECT CONVERT(BIT, 7 & 4)

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.

sql-server-transact-sql
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

ErlandSommarskog avatar image
0 Votes"
ErlandSommarskog answered ErlandSommarskog commented

& 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.


· 2
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Can you give me another example or a web page to read?
Sincerely I never have the need of this "bitwise"... but never say never.
Thanks Alen.

I found this... https://www.mssqltips.com/sqlservertip/1218/sql-server-bitwise-operators-to-store-multiple-values-in-one-column/

0 Votes 0 ·
Monalv-msft avatar image
1 Vote"
Monalv-msft answered

Hi @acappelletti ,

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.



5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.