How compare hex numbers?

Martin v. Löwis martin at v.loewis.de
Sat Dec 14 07:03:55 EST 2002


> I'm trying to compare one hex number with another to see which is
bigger:

There are no hexadecimal integers in Python; the only kinds of integers
is the "plain" integer, and the "long" integer. The integers are objects
that support arithmethic operations (+,-,*,/,<,>, etc). They have
literals, which denote certain integers; those literals can be written
with decimal, octal, and hexadecimal digits.

And now for something completely different: the string object. Strings
do not support arithmetic operations, they only support concatenation
(+), and lexicographical comparison (<, >).

Then, there are conversion functions. hex() has an integer argument
(either short or long), and returns a string object, which is a
hexadecimal *representation* of the number, not the number itself - the
result is a string is a string is a string.

> U = hex(U)

If U was an integer before, it is now a string.

> if U < '0x10000':

Comparing two strings uses lexicographical comparison: '0x2' > '0x10',
just like 'Gustaf' < 'Martin'.

> Python says U is bigger when U is in fact smaller. I've tried other
ways to
> specify that '0x10000' is hexadecimal too, including:
>
> if U < 0x10000:

Now, if U is still a string, you are comparing strings and integers
here. Try guessing what the outcome *should* be, i.e. is 42 smaller or
greater than 'Gustaf'?

> if U < '\x10000':
> if U < hex('0x10000'):
>
> What is the right syntax?

To compare numbers, you should make sure that U is an integer, not a
string. Then you can compare it to another integer, which you might
denote through a hexadecimal *literal*, e.g. 0x10000.

HTH,
Martin




More information about the Python-list mailing list