Thanks, Dave. On the struct module, How can I het the binary 1's and 0's of the Hex value? Let say I want to get the 8 bit value of '\xe2', can I use struct to convert that into binary code so that I get 8 binary bits as a string?
Thanks for helping with struct. Johan -----Original Message----- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of David Perlman Sent: 19 February 2007 05:56 PM To: tutor@python.org Subject: Re: [Tutor] Struct the solution for Hex translation 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 _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor -- No virus found in this incoming message. Checked by AVG Free Edition. Version: 7.5.441 / Virus Database: 268.18.2/692 - Release Date: 2007/02/18 04:35 PM -- No virus found in this outgoing message. Checked by AVG Free Edition. Version: 7.5.441 / Virus Database: 268.18.2/692 - Release Date: 2007/02/18 04:35 PM _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor