import hashlib
def get_shard_index(device_id, total_tables):
try:
# 使用 hashlib 计算 MD5 哈希
md = hashlib.md5()
md.update(device_id.encode('utf-8'))
hash_bytes = md.digest()
# 将字节数组中的每个字节转换为有符号整数并累加
# 使用 struct.unpack() 将每个字节转换为有符号整数
hash_value = sum((b - 256 if b > 127 else b) for b in hash_bytes)
# 计算分片索引并返回
return abs(hash_value) % total_tables
except Exception as e:
print(f"Error: {e}")
return 0
# 测试
print(get_shard_index("442143ca157d", 20))