从整数中获取Cassandra python驱动中的murmur3哈希值

您所在的位置:网站首页 输出不了hex文件 从整数中获取Cassandra python驱动中的murmur3哈希值

从整数中获取Cassandra python驱动中的murmur3哈希值

2023-03-19 22:40| 来源: 网络整理| 查看: 265

如果你不想看我的帖子,简而言之,最简单的解决方案就是用hex(a)来换取整数a即h = Murmur3Token.hash_fn(hex(a))。

你的错误是由于Murmur3Token.hash_fn(...)没有为整数(int)Python类型实现。

通常情况下哈希函数是为散列任何大小的单一字节块而实现的,而不是为任何其他非字节类型。其他类型通常被转换为字节,这被称为序列化.

你的函数同时支持bytes和str类型。你必须以某种方式将你的数字转换成这两种类型中的一种。我已经实现了以下三种转换方案(变体0、1、2)。

Variant 0 is converting to hex string, just do hex(n). This is most simple to use solution, but can be slower than other solutions for large integers, but faster for small integers. This is a very stable solution, meaning that hex representation and hence hash value will never change. Variant 1 is converting to bytes through pickle.dumps(n). This is a bit more complex than previous solution, needing module pickle. It is also faster for large integers but slower for small. Also might be somewhat unstable because pickling format may change some time resulting in different produced bytes and hash. Variant 2 is converting to bytes through implemented by me function to_bytes(n). It is even 1.5x faster than pickle solution for small ints and around same speed for large inputs. This solution is also stable in a sence that unlike pickle format my format will not change (unless you modify my function).

一般来说,如果你只想简单一点,或者你的整数小于1024位,那么就使用hex(n)。如果你的整数非常大(超过1024位),请使用我的函数to_bytes(n),或者你也可以使用hex(n),只是2.5x会慢一些。虽然这可能是相当大的减慢,如果你有很多数据,那么更喜欢to_bytes(n)。

NOTE:我的帖子中描述的三种不同的序列化函数/方式都会产生不同的哈希值。你需要选择其中的一个,并始终使用它来处理你的数字,以便每次产生相同的结果。

我的代码需要通过python -m pip install cassandra-driver timerit matplotlib命令行一次性安装下一个python模块,模块timerit和matplotlib只用于时间/速度测量,以后不需要用于实际的哈希计算。

下面是位于1)代码2)时间测量图3)控制台输出。

Try it online!

# Needs: python -m pip install cassandra-driver timerit matplotlib from cassandra.metadata import Murmur3Token # Input n = 3202012 # ---------- Variant 0, convert to string ---------- print(Murmur3Token.hash_fn(hex(n))) # ---------- Variant 1, convert to bytes using pickle ---------- import pickle print(Murmur3Token.hash_fn(pickle.dumps(n))) # ---------- Variant 2, convert signed int to min num of bytes ---------- def to_bytes(n, order = 'little'): # order can be 'little' or 'big' # Zig-Zag encode signed integer to unsigned integer, i.e. map # 0 to 0, -1 to 1, 1 to 2, -2 to 3, 2 to 4, -3 to 5, 3 to 6, etc n = (n = 0 else (((-n - 1)


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3