[Tutor] Struct the solution for Hex translation

Alan Gauld alan.gauld at btinternet.com
Mon Feb 19 17:24:48 CET 2007

"Johan Geldenhuys" <johan at accesstel.co.za> wrote

>>> data
>>> data[0]
>>> len(data[0])

OK, So that tells you that you have one byte.
The '\xa5' is a 4 character representation of that byte but it
is only one byte with hex value a5. You don;t need to strip
anything, you have your byte.

>>> int(data[0], 16)
  File "<console>", line 1, in ?
''' exceptions.ValueError : invalid literal for int(): ¥ '''

Its already an int (well a byte) you don;t need to use int()

>>> int('a5', 16)

Because that passes the 2 byte string 'a5' to int. But you
don't need that your byte actualoly is a5

> If I use data[0] as it is, I get errors. That why I want to
> know how I can strip away the '\x'.

The \x doesn't exist its purely a part of the replresentation
that Python uses to display the data. Its like the L at the
end of a long interer. The number doesn't really have an L
at the end its just put there by Python to show the type.
Similarly the '\x' is prepended by Python to show that this
is a hex value.

>>> def hexBin(hexchars):
...     s = ""
        for hexchar in hexchars:
            s += hex2bin[hexchar]
        return s.rstrip("\n")
>>> hexBin('a5')

This however does not work if my argument is '\xa5'.

>>> hexBin('\xa5')
  File "<console>", line 1, in ?
  File "<console>", line 5, in hexBin
''' exceptions.KeyError : '\xa5' '''

Because you are now passing a single character which
is not a valid hex character.

So far as I can see you actually have the data you want!

Alan Gauld
Author of the Learn to Program web site

More information about the Tutor mailing list