您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

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

我这样做的方法(通常是在发送到某些硬件之前,通常要确保固定宽度的整数)是通过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)
python 2022/1/1 18:35:49 有457人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶