Converting from long integer to read-only buffer

Bengt Richter bokr at accessone.com
Wed Jul 4 17:56:47 EDT 2001


On 3 Jul 2001 18:57:32 -0800, Ben Andrew Fulton
<bafulton at cats.ucsc.edu> wrote:

>I'm currently working on a module to control a piece of hardware over the
>serial port of a Mac. The command packets are currently manipulated within
>the the module as long integers so that I can twiddle individual bits. 
>However, when I send them out the serial port they need to be converted
>into a read-only buffer (or perhaps a string [although of course, str() 
>is not the answer]) for the ctb (communications toolbox) to accept them.
>Is there a module out there that can do a straight long int --> read-only
>buffer conversion? struct, array, and binascii all seem inadequate to the
>task unless I write my own helper function, which I suppose I will have to
>if I can't figure anything else out in the next day or so. 
>
>Thanks,
>
>-->ben fulton
>
You could write something more efficient, but for a quick test try:

 >>> nOut = 15
 >>> cmdPkts = 65*2L**64/255 # 65 is A and /255 repeats in binary ;-)
 >>> sOut = ''.join([chr((cmdPkts>>k*8)&0xff) for k in  xrange(nOut)])
 >>> sOut
 'AAAAAAAA\x00\x00\x00\x00\x00\x00\x00'

where
  nOut is the size of your output string in bytes (15 arbitrary here)
  cmdPkts is the long integer you have, above with test pattern
  sOut is the output string

Note the order of the string. It is little-endian, taking the LS byte
from the long first. Maybe another example is better:

 >>> cmdPkts = 0L
 >>> for x in xrange(ord('a'),ord('z')+1):
 ...     cmdPkts = (cmdPkts<<8)|x
 ...
 >>> nOut = 28
 >>> sOut = ''.join([chr((cmdPkts>>k*8)&0xff) for k in  xrange(nOut)])
 >>> sOut
 'zyxwvutsrqponmlkjihgfedcba\x00\x00'

The z is first because it was or-ed into cmdPkts at the LSB position.
I chose 28 length to show the padding effect.

HTH




More information about the Python-list mailing list