使用dhash库get_num_bits_different方法时遇TypeError错误求助
Fixing the TypeError in
get_num_bits_different Method Hey there! Let's break down and fix the error you're encountering.
The Root Cause
The error TypeError: unsupported operand type(s) for ^: 'str' and 'str' pops up because you're passing hexadecimal string values (hash1 and hash2) to the function, but the ^ (bitwise XOR) operator only works with integers—not strings. The method expects numeric hash values, not their string representations.
The Solution
You need to convert your hex string hashes into integers first using Python's int() function, specifying base 16 (since the hashes are in hexadecimal format). Here's the corrected code:
def get_num_bits_different(hash1, hash2): # Convert hex string hashes to integers int_hash1 = int(hash1, 16) int_hash2 = int(hash2, 16) # Perform bitwise XOR and count differing bits return bin(int_hash1 ^ int_hash2).count('1') hash1 = '3d77xxxxxxxxxxxxxxxxxxxxxxxxxxxx' hash2 = '9301xxxxxxxxxxxxxxxxxxxxxxxxxxxx' # Now this will work correctly print(get_num_bits_different(hash1, hash2))
How It Works
int(hash1, 16)takes the hex string and converts it to a base-10 integer, making it compatible with bitwise operations.- The
^operator computes the bitwise XOR of the two integers—each bit in the result is 1 only if the corresponding bits of the inputs are different. bin(...)converts the XOR result to a binary string, and.count('1')tallies up how many bits are different (exactly what you need for dhash comparison).
内容的提问来源于stack exchange,提问作者Ancalagon BerenLuthien
相关产品推荐
相关产品推荐

