[Tutor] Re: hex to decimal conversion.

Magnus Lycka magnus@thinkware.se
Sat Nov 16 04:33:02 2002


At 12:12 2002-11-16 +1300, Thomi Richards wrote:
>i think this pretty much sums up my frustrations:

Aha. Examples are always good. Now it's clear what
you haven't understood.

> >>> pal.data[0]
>'\xff'

That's the representation (i.e. result of repr() call) for
a *string* object, nothing else. Note the single quotes
surrounding the value. pal.data[0] does NOT contain a
"hexadecimal vaule" it contains a one character string.

Since values outside the range of printable characters in
ASCII are represented differently depending on platform and
national settings (we ignore EDCBIC for now) characters
outside that range is *represented* like hexadecimal sequences.
 >>> a =3D '=C5'
 >>> print a
=C5
 >>> a
'\xc5'

This is to make sure that it's possible to transfer data verbatim
from one environment to another etc. (The value in the assignment
above should be an A with a ring over it. It might not look like
that when the mail arrives to you depending on your settings or
mail systems on the way to you, but I'm pretty sure the hex value
on the last row, \xc5, will look the same...)

There *is* no such thing as hexadecimal objects. Hexadecimal,
decimal or octal, are just different ways of entering or
displaying *integer* (or long integer) values.

> >>> print pal.data[0]
>=FF

This is how the value 255 (or FF in hex) is shown in the
Latin-1 (and some other?) code pages.

> >>> print '%i' % (pal.data[0])
>Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
>TypeError: an integer is required

Same as if you would do "print '%i' % 'X'

> >>> print '%i' % (int(pal.data[0]))
>Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
>ValueError: invalid literal for int(): =FF

Same as if you would do "print '%i' % int('X')

> >>> int(pal.data[0],16)
>Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
>ValueError: invalid literal for int(): =FF

Same as if you would do "print '%i' % int('X', 16)

A string describing hex that you convert to integer can
only contain digits or a-f (or A-F). Not =FF. Right?

>_what_ am i doing wrong here?

You haven't studied the builtin functions in python! ;)
Read through that little chapter in the Python Library
Reference (2.1). Pay special attention to the functions
ord() "ordinal" and it's inverse chr() "character", but
learning most of the functions is a good thing. :)

 >>> a =3D '=FF'
 >>> a
'\xff'
 >>> print a
=FF
 >>> ord(a)
255
 >>> print "%i" % ord(a)
255
 >>> print "%o" % ord(a)
377
 >>> print "%x" % ord(a)
ff
 >>> print "%X" % ord(a)
FF
 >>> a =3D=3D chr(ord(a))
1
 >>> for i in range(256):
...     print i, chr(i), repr(chr(i))
...



--=20
Magnus Lycka, Thinkware AB
Alvans vag 99, SE-907 50 UMEA, SWEDEN
phone: int+46 70 582 80 65, fax: int+46 70 612 80 65
http://www.thinkware.se/  mailto:magnus@thinkware.se