1

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?

2 Answers 2

1

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)

Sign up to request clarification or add additional context in comments.

10 Comments

So it's saying that the bit "2" is present in both 6 and 51, even though 4 is not?
Yes. 6=4+2; 51=32+16+2+1
So 4 & 51 is 0 because 4: 000100 and 51: 110011, and the bit in 4 isn't used in 51?
@imperium2335 yes, exactly.
So 4 | 51 would return 4 because 000100 is in 4?
|
0

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

2 Comments

So Mysql goes right to left and not left to right like PHP?
@imperium2335 . . . The documentation describes "1 << 2" as 4. I don't know how PHP defines this construct, but this does but the low-order bits on the right.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.