Reputation: 53
>>> var = 'g'
>>> print hex(ord(var))
0x67
>>> print hex(ord(var)) == 0x67
False
Why isn't this true in python 2.7?
What would be the best way to compare 'g' to the hex value 0x67?
Upvotes: 2
Views: 3638
Reputation: 11134
First see the type of hex(ord(var))
:
>>> print type(hex(ord(var)))
<type 'str'>
Then see the type of 0x67
>>> type(0x67)
<type 'int'>
You are comparing a str
with an int
. So, you should do:
hex(ord(var)) == '0x67'
Upvotes: 0
Reputation: 12547
According to the documentation
hex(x)
Convert an integer number (of any size) to a lowercase hexadecimal string prefixed with
0x
So hex(ord(var)) == '0x67'
It just print
that removes quotes.
See
>>> var = 'g'
>>> hex(ord(var))
'0x67'
>>> hex(0x67)
'0x67'
>>> hex(ord(var)) == hex(0x67)
True
And of course ord(g) == 0x67
because numbers are equal despite of representation, i.e 0x67 and 103 and 0147 are all the same number internally
Upvotes: 0
Reputation: 26580
You can simply take the ord and compare it to 0x67
>>> ord('g') == 0x67
True
If you do this:
>>> 0x67
103
You are still getting the ascii code for that character.
Furthermore, based on your explicit example, if you are trying to cast that to an int to actually compare to 0x67, then you need to do it in base-16:
>>> int(hex(ord('g')), 16) == 0x67
True
False case:
>>> int(hex(ord('d')), 16) == 0x67
False
Upvotes: 0
Reputation: 126867
hex
returns a string, which you are comparing to a number. Either do
ord(var) == 0x67
or
hex(ord(var)) == "0x67"
(the first one is less error-prone, as it's case insensitive)
Upvotes: 1