You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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

  1. int(hash1, 16) takes the hex string and converts it to a base-10 integer, making it compatible with bitwise operations.
  2. 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.
  3. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 06:45:18