简体   繁体   中英

MYSQL Bitwise operations

I am trying to understand bitwise operators in MySQL.

I have:

SELECT 1 & 51 FROM bits = 1
SELECT 2 & 51 FROM bits = 2
SELECT 3 & 51 FROM bits = 3
SELECT 4 & 51 FROM bits = 0
SELECT 5 & 51 FROM bits = 1
SELECT 6 & 51 FROM bits = 2

With SELECT 1 & 51 FROM bits is this asking that the first bit (1) is present in both 1 and 51, if it is then I understand this.

But SELECT 6 & 51 FROM bits = 2 doesn't make sense to me as the 6th bit would be 32(?) which isn't is 6, as 6 is made from the 2nd and 4th bit(?), but 32 is present in 51.

So I am a bit confused as to how this works, could someone please explain?

"6" doesn't refer to the sixth bit. It refers to the binary value. With 8 bits: 00000110.

If you want the sixth bit, use either 1<<6 or 32.

The two arguments aren't the indexes of the bits - it means you represent each number in binary, and perform the operation between each bit independently.

 6 in binary: 000110
51 in binary: 110011
AND           ======
              000010

The result, 000010 , is the binary representation of 2.

(Note the the preceeding zeros were truncated for clarity's sake)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM