How to create a fixed size (unsigned) integer in python?

后端 未结 4 973
渐次进展
渐次进展 2021-01-13 02:39

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 mem

4条回答
  •  长情又很酷
    2021-01-13 03:40

    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)
    

提交回复
热议问题