python int占几个字节

Python011

python int占几个字节,第1张

《深入理解计算机系统》这本书上面提到了在32位机器和64机器中int类型都占用4个字节。《The C Programming language》这本书,里面有一句话是这样的:Each compiler is free to choose appropriate sizes for its own hardware, subject only to the restriction that shorts and ints are at least 16bits, longs are at least 32bits, and short is no longer than int, which is no longer than long.意思大致是编译器可以根据自身硬件来选择合适的大小,但是需要满足约束:short和int型至少为16位,long型至少为32位,并且short型长度不能超过int型,而int型不能超过long型。这即是说各个类型的变量长度是由编译器来决定的,而当前主流的编译器中一般是32位机器和64位机器中int型都是4个字节(例如,GCC)。

相关推荐:《Python教程》

下面列举在GCC编译器下32位机器和64位机器各个类型变量所占字节数:

需要说明一下的是指针类型存储的是所指向变量的地址,所以32位机器只需要32bit,而64位机器需要64bit。

int.to_bytes( length , byteorder , * , signed=False ) byteorder  可取值    big    或    little

(1).to_bytes(1, byteorder='big')

b'\x01'

(1).to_bytes(2, byteorder='big')

b'\x00\x01'

(1).to_bytes(3, byteorder='big')

b'\x00\x00\x01'

c=b'\x00\x00\x03\x84'

d=int.from_bytes(c, byteorder='big')

900

以python3版本为例说明, int 类型在python中是动态长度的。因为python3中int类型是长整型,理论支持大的数字,但它的结构其实也很简单, 在 longintepr.h 中定义:

struct _longobject {

PyObject_VAR_HEAD

digit ob_digit[1]

}

这结构是什么意思呢,重点在于 ob_digit 它是一个数组指针。digit 可认为是 int的别名。python的整型存储机制是这样的。比方要表示一个很大的数:123456789 。而每个元素只能表示3位十进制数(为理解打的比方)。那么python就会这样存储:

ob_digit[0] = 789

ob_digit[1] = 456

ob_digit[2] = 123

低位存于低索引下。python中整型结构中的数组,每个元素存储 15 位的二进制数(不同位数操作系统有差异32位系统存15位,64位系统是30位)。

因此,sys.getsizeof(0) 数组元素为0。此时占用24字节(PyObject_VAR_HEAD 的大小)。 sys.getsizeof(456) 需使用一个元素,因此多了4个字节。