如何在python中创建一个固定大小(无符号)整数? [英] How to create a fixed size (unsigned) integer in python?

查看:599
本文介绍了如何在python中创建一个固定大小(无符号)整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to create a fixed size integer in python, for example 4 bytes. Coming from a C background, I expected that all the primitive types will occupy a constant space in memory, however when I try the following in python:

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

我得到

>>>24  
>>>52

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

respectively.
How can I create a fixed size (unsigned) integer of 4 bytes in python? I need it to be 4 bytes regardless if the binary representation uses 3 or 23 bits, since later on I will have to do byte level memory manipulation with Assembly.

推荐答案

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

the way I do this (and its usually to ensure a fixed width integer before sending to some hardware) is via 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

否则结构可以做到

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

这篇关于如何在python中创建一个固定大小(无符号)整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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