How compare hex numbers?

Ken Seehof kseehof at neuralintegrator.com
Sat Dec 14 20:17:09 EST 2002


At 03:41 AM 12/14/2002 Saturday, Gustaf Liljegren wrote:
>I'm trying to compare one hex number with another to see which is bigger:
>
>U = hex(U)
>if U < '0x10000':
>   print "U is smaller."
>else:
>   print "U is bigger."
>
>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:
>if U < '\x10000':
>if U < hex('0x10000'):
>
>What is the right syntax?
>
>Gustaf

I recommend that you spend a bunch of time experimenting
in the python shell.  You need to develop a clear intuitive
distinction between strings and integers in particular.

There is a funny quirk in python: objects of different types can
be compared (in most languages it's an error).  It turns out that
there are good reasons for this, which I won't get into here (hint:
it has to do with sorting lists).  It can be confusing though.  In
particular, strings and integers can be compared, and the result
will not depend on the values!  In fact strings are always greater
than integers, though this is not defined in the language spec,
so in some other python implementation, integers could be
always greater than strings.

Try the following expressions and see if they give the results
you expect.  Continue playing with it until you can consistently
predict all of the results in advance.  Note that boolean expressions
return 0 or 1, so you don't need to use "if" to test them.

'12' > '2'
int('A', 16)
int('0xA', 16)
hex(10)
int('0xA', 16) == 10
hex(10) == 16
1=='1'
9999<'1'
1<'99999'

- Ken






More information about the Python-list mailing list