Converting from long integer to read-only buffer

Darrell news at dorb.com
Wed Jul 4 14:26:28 EDT 2001


The one liner approach :)
Hope the Python is adding features too fast forces, don't use this an
example of evil.

import re, time

x=0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
ffffffffffffffffffffffaL
t1=time.time()

# I didn't cut off the trailing 'L' returned by hex(x). It's needed for the
pattern("..")
# It ensures that all digits are found
# In the case of odd number of digits 'fL' is found which is evaluated as
0xfL
binData = ''.join([chr(eval('0x'+val)) for val in
re.findall('..|.',hex(x)[2:-1])])

# Iterators will provide a new and fun approach to this.
binData = ''.join([chr(eval('0x'+val)) for val in
re.findall('..',hex(x)[2:])])

print "Len:", len(binData)
print time.time()-t1
print binData

xRet = eval('0x'+''.join([hex(ord(val))[2:] for val in list(binData)])+'L')
assert(xRet==x)
print hex(xRet)

--Darrell

"Ben Andrew Fulton"
> 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
>





More information about the Python-list mailing list