Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 683
George Avatar asked Oct 31 '13 20:10

George


2 Answers

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.

like image 193
Simeon Visser Avatar answered Sep 20 '22 10:09

Simeon Visser


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)
like image 28
Naib Avatar answered Sep 18 '22 10:09

Naib