简体   繁体   中英

Mysql convert varchar binary representation field to binary to do hamming distance calculation with bit_count

I've a db table with a varchar(64) field to store PHashing data, as 64 chars (1's and 0's ascii characters). I need to calculate hamming distance with a test hasta, and it seems that the most efficient way to do is using mysql bit_count function. The problem is that I haven't found any way to convert/cast/whatever the hash field in order to be interpreted as a byte(8) instead of varchar(64). Like:

> select hash from data;
"0000000101100111111100011110000011100000111100011011111110011011"
> select convert_to_binary(hash) from data;
0b0000000101100111111100011110000011100000111100011011111110011011

I cannot alter the data and convert all previous data into a binary field. Is there any way to force mysql to re-interpret a field as a literal, or any other alternative solution?

I think you should be able to use it like this:

SELECT BIT_COUNT(CAST(hash AS BINARY)) FROM data;

Use CAST to convert the field to BINARY and pass the result to BIT_COUNT . Casting the field hash to binary will turn it into a string with the binary data type, but BIT_COUNT is able to handle that.

Working code:

SELECT BIT_COUNT( CONV( hash, 2, 10 ) ^ 
0b0000000101100111111100011110000011100000111100011011111110011011 )

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