[Edu-sig] Advanced or beginner?

Kirby Urner pdx4d@teleport.com
Tue, 31 Jul 2001 23:57:01 -0700


When teaching Python, do we begin with a treatment of
low level representations of data?  Or is that saved for
a later time?

For example:

   >>> import struct,array,sys
   >>> sys.byteorder
   'little'
   >>> m = array.array('I','THIS')
   >>> m
   array('I', [1397311572L])
   >>> k = [hex(ord(i))[2:] for i in 'THIS']
   >>> k.reverse()
   >>> k
   ['53', '49', '48', '54']
   >>> k = "".join(k)
   >>> k
   '53494854'
   >>> eval('0x'+k)
   1397311572
   >>> struct.pack('i',1397311572)
   'THIS'

Basically, I'm taking the string 'THIS' and converting
it to an integer.  The way this is done internally
corresponds to concatenating 4 hex bytes in reverse
order, i.e. 'T' = 0x54:

   >>> ord('T')
   84
   >>> hex(84)
   '0x54'

Link those bytes to return a bigger number in decimal
form (1397311572).  Then tell struct it's reading an
integer, which it returns as a corresponding string:
lo and behold, our THIS is returned to us.

Kirby