Odd problem with converting string to Hex?

Steve Holden sholden at holdenweb.com
Sun Jul 1 15:34:32 EDT 2001

"Benjamin Schollnick" <junkster at rochester.rr.com> wrote in ...
> Folks,
>    This is odd.... or at least I think it is....
>    Using Python v2.1....
>    Here's a snippet of the data:
> ('.', '\x00\x90\x83H\x11\x0f'),
> ('.', '\x00\x90\x83H\x11\x0f'),
> ('.', 'RF Upstream Interface')
>    I've tried using:
>       eval (data[1])
>       hex (data[1])
>       str(data[1])
>    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
> python.org.....
Nope. There *is* no"\x" in the string. Look:

>>> d = ('.', '\x00\x90\x83H\x11\x0f')
>>> len(d[1])

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[1]]
[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[1]]
['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[1]])

Hope this helps.


More information about the Python-list mailing list