[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
'\xa5\x16\x0b\x0b\x00\xd5\x01\x01\x01\x00\x00\xe3\x84(\x01\xc6\x00\x00\x17\x
01C\xc7'
>>> data[0]
'\xa5'
>>> len(data[0])
1
>>>

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)
165

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')
'10100101'

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
http://www.freenetpages.co.uk/hp/alan.gauld




More information about the Tutor mailing list