how many bytes in an int

Reid Nichol rnichol_rrc at yahoo.com
Mon Aug 9 13:51:39 EDT 2004


Martin v. Löwis wrote:
> As Grant says: use the struct module. Use struct.calcsize to find out
> how large an int is. If the size is too large, try a short. If the size
> is too small, try a long. If no type matches, take the next larger type,
> and drop the extra bytes.
> 
> However, it does not actually need to be that difficult: "int" is 32-bit
> on all current systems, including all 64-bit systems (only long is 
> 64-bits on some 64-bit systems).
> 
> Regards,
> Martin

Thanks to all who helped.  This is my solution (maybe overkill) but I 
plan on adding read/write functions, etc (of course its just a first 
thought).  It seems to work, so any feedback is appreciated.

#!/usr/bin/env python
from struct import *

class FixedSizeInteger:
         def __init__(self, length_in_bytes, endianness='@'):
                 self.fmt = ''
                 self.endianness = endianness

                 # find the length_in_bytes byte datatype
                 for type in ['h', 'i', 'l', 'q']:
                         if length_in_bytes == calcsize(type):
                                 self.fmt = endianness + type

		# should throw an exception here
                 if self.fmt == '':
                         print 'ERROR: type not found'

         def printFmt(self):
                 print 'My format is ' + self.fmt


if __name__ == '__main__':
         test = FixedSizeInteger(4)

         test.printFmt()



More information about the Python-list mailing list