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

后端 未结 4 915
渐次进展
渐次进展 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:21

    You can use struct.pack with the I modifier (unsigned int). This function will warn when the integer does not fit in four bytes:

    >>> from struct import *
    >>> pack('I', 1000)
    '\xe8\x03\x00\x00'
    >>> pack('I', 10000000)
    '\x80\x96\x98\x00'
    >>> pack('I', 1000000000000000)
    sys:1: DeprecationWarning: 'I' format requires 0 <= number <= 4294967295
    '\x00\x80\xc6\xa4'
    

    You can also specify endianness.

    0 讨论(0)
  • 2021-01-13 03:26

    I have no idea if there's a better way to do this, but here's my naive approach:

    def intn(n, num_bits=4):
        return min(2 ** num_bits - 1, n)
    
    0 讨论(0)
  • 2021-01-13 03:39

    you are missing something here I think

    when you send a character you will be sending 1 byte so even though

    sys.getsizeof('\x05') 
    

    reports larger than 8 you are still only sending a single byte when you send it. the extra overhead is python methods that are attached to EVERYTHING in python, those do not get transmitted

    you complained about getsizeof for the struct pack answer but accepted the c_ushort answer so I figured I would show you this

    >>> sys.getsizeof(struct.pack("I",15))
    28
    >>> sys.getsizeof(c_ushort(15))
    80
    

    however that said both of the answers should do exactly what you want

    0 讨论(0)
  • 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)
    
    0 讨论(0)
提交回复
热议问题