[Tutor] Struct the solution for Hex translation
David Perlman
dperlman at wisc.edu
Mon Feb 19 16:56:09 CET 2007
You're way off base... :)
On Feb 19, 2007, at 9:25 AM, Johan Geldenhuys wrote:
> Here is what I have:
>
>>>> 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
>>>>
>
> You see that data[0] is only one byte and it doesn't see all four
> characters.
>
> If I want to do this:
>
>>>> int(data[0], 16)
> File "<console>", line 1, in ?
> ''' exceptions.ValueError : invalid literal for int(): ¥ '''
>
>
> But I can do this:
>
>>>> int('a5', 16)
> 165
>>>>
>
> If I use data[0] as it is, I get errors. That why I want to know
> how I can
> strip away the '\x'.
This is what you want to do:
>>> import struct
>>> struct.unpack('B',data[0])
(165,)
Once again, the \x doesn't really exist, any more than the quotation
marks do. They're just ways of indicating on the screen what kind of
data is being displayed.
> Here is some other code to convert Hex to Binary:
>
> hex2bin = {
> "0" : "0000", "1" : "0001", "2" : "0010", "3" : "0011",
> "4" : "0100", "5" : "0101", "6" : "0110", "7" : "0111",
> "8" : "1000", "9" : "1001", "a" : "1010", "b" : "1011",
> "c" : "1100", "d" : "1101", "e" : "1110", "f" : "1111"
> }
>
>>>> 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' '''
>>>>
This function is useless in this case because you don't actually have
a string of letters and numbers; you just have raw binary data.
--
-dave----------------------------------------------------------------
After all, it is not *that* inexpressible.
-H.H. The Dalai Lama
More information about the Tutor
mailing list