David
David

Reputation: 1908

Trouble doing a bitwise xor + bit_count in mysql

I am trying to perform a comparison on hash values (hexadecimal strings of 16 characters). I have a MYSQL table that stores those values with a phash VARCHAR(16) column. This is what I am trying to do:

SELECT phash, bit_count(phash ^ x'dda15873a3de013d') FROM mytable;

But the bit_count + xor is not done correctly. Even for phash='dda15873a3de013d' I get 33 as a result whereas I should get 0 (the two hex are the same, so the xor should yield only zeros, hence a bit_count of 0.

What is wrong? Thank you

Edit: example here => http://sqlfiddle.com/#!9/d7f5c2/1/0

mysql> SELECT phash,BIT_COUNT(CONV(phash, 16, 10) ^ 0xdda15873a3de012d) from mytable limit 1;

+------------------+-----------------------------------------------------+
| phash            | BIT_COUNT(CONV(phash, 16, 10) ^ 0xdda15873a3de012d) |
+------------------+-----------------------------------------------------+
| dda15873a3de012d |                                                  33 |
+------------------+-----------------------------------------------------+

Upvotes: 0

Views: 734

Answers (3)

b1rdex
b1rdex

Reputation: 3

SELECT BIT_COUNT(cast(CONV(phash, 16, 10) as unsigned) ^ 0xdda15873a3de013d)

Upvotes: 0

John Kerl
John Kerl

Reputation: 61

CONV returns a string. You need to cast the result of CONV to UNSIGNED.

Upvotes: 1

user149341
user149341

Reputation:

The MySQL ^ operator only works on integers. It can't be used to XOR strings (or blobs) with each other.

If your strings specifically represent hexadecimal integers, you can use ^ after converting them to integers:

SELECT BIT_COUNT(CONV(phash, 16, 10) ^ 0xdda15873a3de013d)

Upvotes: 0

Related Questions