Odd problem with converting string to Hex?
sholden at holdenweb.com
Sun Jul 1 21:34:32 CEST 2001
"Benjamin Schollnick" <junkster at rochester.rr.com> wrote in ...
> This is odd.... or at least I think it is....
> Using Python v2.1....
> Here's a snippet of the data:
> ('.188.8.131.52.184.108.40.206.1.6.2', '\x00\x90\x83H\x11\x0f'),
> ('.220.127.116.11.18.104.22.168.1.6.1', '\x00\x90\x83H\x11\x0f'),
> ('.22.214.171.124.126.96.36.199.1.2.4', 'RF Upstream Interface')
> I've tried using:
> eval (data)
> hex (data)
> What gets returned is:
> Unknown - Mac? ---> êÉH
> Hex: Long:
Let's get this straight. Your data records MAC-level addresses as six-byte
strings, and you want to represent each address as a set of byte values, in
hex, separated by dashes. OK so far?
> Which os definetly not what I'm looking for.... I'm attempting to
> decode this in pure hexadecimal...
> I suspect it's due to the "\x" in the string, but I can't pull up the
> documentation, since when I tried I wasn't getting a response from
Nope. There *is* no"\x" in the string. Look:
>>> d = ('.188.8.131.52.184.108.40.206.1.6.2', '\x00\x90\x83H\x11\x0f')
Each \xXX (where the XX are hex digits) is made into a single 8-bit
character by the Python interpreter. The "H" is also a character. Let's look
at the decimal values of each character:
>>> [ord(x) for x in d]
[0, 144, 131, 72, 17, 15]
Given the hex values in your data this seems reasonable.
> Conceptually I'm trying to output it, similiar to:
> 00-90-83-11-0f Assuming I'm reading the returned data properly.
That appears to be the problem: you assumed that Python was storing
everything inside the single quotes as individual bytes, when in fact the
hex escape sequences are interpreted as the string is constructed.
Getting the hex values is relatively easy using string formatting:
>>> ['%02x' % ord(x) for x in d]
['00', '90', '83', '48', '11', '0f']
All you have to do to get what you want is join this list of strings with
dashes. I tend to favor the string methods for this kind of thing, though
some say it seems counterintuitive:
>>> "-".join(['%02x' % ord(x) for x in d])
Hope this helps.
More information about the Python-list