简体   繁体   中英

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 |
+------------------+-----------------------------------------------------+

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

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)
SELECT BIT_COUNT(cast(CONV(phash, 16, 10) as unsigned) ^ 0xdda15873a3de013d)

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