python中定义无符号整数_如何在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)

I get

>>>24

>>>52

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.

解决方案

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

otherwise struct can do it

from struct import pack, unpack

pack_type = {'signed':'>h','unsigned':'>H',}

pack(self.pack_type[sign_type], data)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值