如何在python中创建固定大小(无符号)整数?


问题内容

我想在python中创建一个固定大小的整数,例如4个字节。来自C背景,我希望所有原始类型都将在内存中占据一个恒定的空间,但是当我在python中尝试以下操作时:

import sys  
print sys.getsizeof(1000)
print sys.getsizeof(100000000000000000000000000000000000000000000000000000000)

我懂了

>>>24  
>>>52

分别。
如何在python中创建4字节的固定大小(无符号)整数?无论二进制表示使用3位还是23位,我都需要将其设置为4个字节,因为稍后我将不得不使用Assembly进行字节级的内存操作。


问题答案:

我这样做的方法(通常是在发送到某些硬件之前,通常要确保固定宽度的整数)是通过ctypes

from ctypes import c_ushort

def hex16(self, data):
    '''16bit int->hex converter'''
    return  '0x%004x' % (c_ushort(data).value)
#------------------------------------------------------------------------------      
def int16(self, data):
    '''16bit hex->int converter'''
    return c_ushort(int(data,16)).value

否则struct可以做到

from struct import pack, unpack
pack_type = {'signed':'>h','unsigned':'>H',}
pack(self.pack_type[sign_type], data)