Python - string to hexbytes conversion - HELP!

Steven Majewski sdm7g at Virginia.EDU
Wed Dec 5 18:30:01 EST 2001


On Wed, 5 Dec 2001, William Park wrote:

> On Wed, Dec 05, 2001 at 08:48:39PM +0000, me wrote:
> > I'm a newbie to Python and I am trying to convert a string of decimal
> > numbers - read from raw_input to a series of hexbytes
> > eg
> > if I do a read and get a='1234567'
> > I need  an equivalent string to be
> > b=Chr(0x01)+chr(0x23)+chr(x045)+chr(0x67)
> >
> > all this is to control a device from the serial port but I cannot seem
> > to recall how to conver the input to my required output An hints or
> > suggestion most appreciated! I've spend hours trying various built
> > in's which I would prefer to use
> >
> > HELP!
>
> hex(int('1234567'))
>

If I understand the question, then I think he wants something more like:

  int('1234567',16)

i.e. interpreting the string '1234567' as a string of hex digits (base 16).


I'm a little confused by the rest of the example.
I THINK what he wants as output could be produced by:

>>> from array import array
>>> ia = array( 'i', [ int('1234567',16) ] )
>>> ia
array('i', [19088743])
>>> ia.tostring()
'\x01#Eg'


But if he really needs it broken up into bytes, he can <I>equivalence</I>
it to a byte array:

>>> ba = array( 'b' )
>>> ba.fromstring( ia.tostring() )
>>> ba
array('b', [1, 35, 69, 103])


Verify:

>>> ba.tostring()
'\x01#Eg'
>>> map( hex, ba )
['0x1', '0x23', '0x45', '0x67']



-- Steve






More information about the Python-list mailing list