简体   繁体   中英

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. I'm using 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. 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?

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() . 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:

x = 123456789
x % 2**16
52501

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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