简体   繁体   English

python中有一个函数来获取任意精度数的大小吗?

[英]Is there a function in python to get the size of an arbitrary precision number?

I'm working on a cryptographic scheme in python, so I use arbitrary precision numbers ( long ) all the time. 我正在使用python中的加密方案,所以我一直使用任意精度数字( long )。 I'm using python 2.7. 我正在使用python 2.7。

My problem is that I need to get the most significant two bytes (16 bits) of a number and check if they are the padding I inserted. 我的问题是我需要得到一个数字的最重要的两个字节(16位)并检查它们是否是我插入的填充。 I've tried sys.getsizeof() but that gives the size of the entire object and guess I could also iterate through every few bits of the number until there are only two bytes left, but is there a more pythonian way of doing this? 我已经尝试了sys.getsizeof()但是它给出了整个对象的大小,并猜测我还可以遍历数字的每几位,直到只剩下两个字节,但是有更多的pythonian方式吗?

Thanks in advance. 提前致谢。

This should do it for you: 这应该为你做:

>>> n = 1 << 1000
>>> n.bit_length()
1001
>>> n >> (n.bit_length() - 16)
32768L

Use long.bit_length() . 使用long.bit_length() Eg: 例如:

% long.bit_length(1024L)
11

Or: 要么:

% 1024L.bit_length()
11

To get the first 2 bytes, assuming "first" means "least significant", use modulo 16: 要获得前2个字节,假设“first”表示“最低有效”,请使用模16:

x = 123456789
x % 2**16
52501

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM