Python 中值的字节精度?
我在Python中有一个哈希函数。 它返回一个值。
如何查看此返回值的字节大小?我想知道它是 4 字节还是 8 字节还是什么。
原因:
- 我要确保最小值为0,最大值为2**32,否则我的计算不正确。
- 我想确保将其打包到 I 结构(无符号整数)是正确的。
更具体地说,我正在调用 murmur.string_hash(`x`)。 我想知道是否得到了 4 字节无符号返回值。如果我有不同大小的值,我的计算就会变得混乱。所以我想对其进行健全性检查。
I have a hash function in Python.
It returns a value.
How do I see the byte-size of this return value? I want to know if it is 4-bytes or 8 or what.
Reason:
- I want to make sure that the min value is 0 and the max value is 2**32, otherwise my calculations are incorrect.
- I want to make sure that packing it to a I struct (unsigned int) is correct.
More specifically, I am calling murmur.string_hash(`x`)
.
I want to know sanity-check that I am getting a 4-byte unsigned return value. If I have a value of a different size, them my calculations get messed up. So I want to sanity check it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果是返回数字的任意函数,则只有 Python 中的 4 种标准数字类型:小整数(C 长整型,至少 32 位)、长整型(“无限”精度)、浮点数(C 双精度)和复数。
如果您指的是内置
哈希
,它返回一个标准整数(C 长):如果您想要不同的哈希值,请查看
hashlib
。If it's an arbitrary function that returns a number, there are only 4 standard types of numbers in Python: small integers (C long, at least 32 bits), long integers ("unlimited" precision), floats (C double), and complex numbers.
If you are referring to the builtin
hash
, it returns a standard integer (C long):If you want different hashes, check out
hashlib
.一般来说,在 Python 中将返回值视为特定的字节精度并不是最好的方法,尤其是对于整数。对于大多数意图和目的,Python“短”整数与“长”(无限)整数无缝集成。根据需要将变量从较小的类型提升为较大的类型以保存所需的值。函数不需要返回任何特定类型(例如,同一函数可以根据输入返回不同的数据类型)。
当某个函数由第三方包提供时(就像这个),您可以只信任文档(据我所知,Murmur 表示 4 字节整数)或在使用它之前自己测试返回值(无论是通过
if
、assert
还是try
,具体取决于您的偏好)。Generally, thinking of a return value as a particular byte precision in Python is not the best way to go, especially with integers. For most intents and purposes, Python "short" integers are seamlessly integrated with "long" (unlimited) integers. Variables are promoted from the smaller to the larger type as necessary to hold the required value. Functions are not required to return any particular type (the same function could return different data types depending on the input, for example).
When a function is provided by a third-party package (as this one is), you can either just trust the documentation (which for Murmur indicates 4-byte ints as far as I can tell) or test the return value yourself before using it (whether by
if
,assert
, ortry
, depending on your preference).