pythonintfixed-size-types

How to create a fixed size (unsigned) integer in 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.


Solution

  • 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)