Python - string to hexbytes conversion - HELP!

Peter Hansen peter at
Wed Dec 5 23:13:10 EST 2001

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

I read this as "convert a string of ASCII characters
representing digits in a hexadecimal number" and assumed
because of the device-control aspect it was intended
to produce exactly four bytes.

(In other words, I assume when you said "decimal numbers" 
you didn't mean it, because your example could just as well
have asked to convert '123abc45' which is not just decimal
numbers.  In addition, there's no such thing as a hexbyte,
since bytes are bytes.  Calling them characters is probably
more likely to be understood, but bytes is good too.)

> 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

Try this:

>>> import struct
>>> struct.pack('>L', long('1234567', 16))
>>> chr(0x1)+chr(0x23)+chr(0x45)+chr(0x67)

Note that some of the other methods posted are more general
(handling arbitrary lengths of strings), but at least one
would not work with values higher than 0x7fffffff because
Python ints are signed.

This method is also intended to ensure that the bytes
are produced in the same order you indicated ("big endian")
rather than being platform-dependent.

Peter Hansen, P.Eng.
peter at

More information about the Python-list mailing list