获取Python中整数的大小 [英] Get size of integer in Python

查看:86
本文介绍了获取Python中整数的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何找出某个数字占用的字节数,例如对于\x00-\xFF,我希望得到1(字节),\x100-\xffff会给我2(字节),依此类推。有任何线索吗?

How can I find out the number of Bytes a certain number takes up to store e.g. for \x00 - \xFF I'm looking to get 1 (Byte), \x100 - \xffff would give me 2 (Bytes) and so on. Any clue?

推荐答案

您可以使用简单的数学运算:

You can use simple math:

>>> from math import log
>>> def bytes_needed(n):
...     if n == 0:
...         return 1
...     return int(log(n, 256)) + 1
...
>>> bytes_needed(0x01)
1
>>> bytes_needed(0x100)
2
>>> bytes_needed(0x10000)
3

这篇关于获取Python中整数的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆