[Tutor] Struct the solution for Hex translation
alan.gauld at btinternet.com
Mon Feb 19 16:04:21 CET 2007
"Johan Geldenhuys" <johan at accesstel.co.za> wrote
> The first two bytes of the data is a 16 bit value. Eg: "\xe2\x01'
> I can the first byte into binary if I use 'e2', but I don't know
> how to get the '\x' out of the first byte to use it in python.
Are you sure it is there?
Usually the \x is only part of the repr string, its not actually
in the data. What do you get is you do:
byte = data # get the first byte
print len(byte) # should only be one byte
print byte # should get '\xe2' or whatever.
> My data has the '\x' and all I need is the 'e2'.
If you do have the \xe2 that implies you have 4 characters,
ie 4 bytes, so to get the real value use int(data[2:],16)
> Any advice of the usage of the struct module or how
> I can get rid of the '\x' in my data?
I'm not sure where the struct module comes in? Are
you using struct to read the data? If so you should be
able to use unpack the data into the format you need
by specifying a format string.
Should return two characters(bytes) and a 98 character
string. Like so:
('\x12', '#', 'abcde')
Is that what you want?
Notice that the first value is actially a single byte of
value 12 hex. The \x are only in the display.
The >>> prompt is a great place to experiment with struct
format strings etc.
Author of the Learn to Program web site
More information about the Tutor