[Tutor] Hex conversion strangeness

John Fouhy john at fouhy.net
Thu May 25 00:29:21 CEST 2006


On 25/05/06, Andrew Robert <andrew.arobert at gmail.com> wrote:
> If the 0X21 is the actual hex value, then why convert to integer?
>
> Is this the ASCII table reference to the hex value?

Hi Andrew,

There is a difference between a number and the representation of that number.

For example, there is a number that, in base 10, I can represent as
"33".  In base 8, that number is represented as "41".  In base 2, it
would be "100001".  If I were, say, an ancient Mayan, it might look
quite different indeed (http://en.wikipedia.org/wiki/Maya_numerals).

But in all cases, the number is the same.

So, in python, the hex() and oct() functions will give you the
hexadecimal and octal representations of an integer.  Notice that they
return strings, not numbers.

If you want to convert from a string to an integer, you can use the
int() function with a second parameter.  That's what's happening when
you type int('21', 16) or int('0x21', 16).  You're converting the
string to an integer, which happens to be represented internally by a
bitstring.

Because you're working at the interactive prompt, python automatically
displays the result of every expression you type.  In this case, the
result of int('0x21', 16) is an integer, and python displays integers
in base 10 by default --- hence, you see 33.

By the way, you can enter integers in base 8 or base 16, if you want:

>>> 0x21, 041
(33, 33)
>>> 0x21 is 041 is 33
True

HTH!

-- 
John.


More information about the Tutor mailing list