0

I searched some questions and answers about this topic: How to convert the hex string to hex numberic in python,for example:

hex_str = a1b2c3d4
result = int(hex_str,16)
hex_num = hex(result)
type(hex_num) #i got the 'str' type

As you see above,i think hex_num shoudle be 0xa1b2c3d4, and i can compare it with 0xa1b2c3d4 and will print matched string

if hex_num == 0xa1b2c3d4:
    print 'matched'

but, the code can not run to line 'print' sentence.

4
  • 1
    There is no such thing as a "hex numeric". There are int objects Commented Dec 25, 2018 at 9:31
  • You can create a class Hex(int) which implements whatever methods you desire (e.g. __str__). Commented Dec 25, 2018 at 9:32
  • note that 2712847316 == 0xa1b2c3d4 evaluates to True. At the end of the day, all numbers are really binary internally. Python emphasizes this concept by treating representations and actual numbers well defined. int objects display all values in base 10, unless you use some other representation (such as hex), but all representations convert to the same int object for arithmetic. Commented Dec 25, 2018 at 9:39
  • so, if i want to compare two numberic are equal or not,i have to convert them to int Commented Dec 26, 2018 at 1:44

1 Answer 1

4

hex() returns a string

>>> hex(123)
'0x7b'

>>> type(hex(123))
<class 'str'>

Python treats hex numbers as int

>>> 0xabc123
11256099

>>> type(0xabc123)
<class 'int'>

>>> 0xabc123 + 1
11256100

If you want hex_num variable match with the number 0xa1b2c3d4 you don't need to use hex().

hex_str = 'a1b2c3d4'  # I write in quotes, otherwise get "not defined" error
result = int(hex_str, 16)

if result == 0xa1b2c3d4:
    print('matched')

Alternatively if you want to work with the hex representation you need to compare it with the string, use quotes in the if statement.

hex_str = 'a1b2c3d4'
result = int(hex_str, 16)

hex_num = hex(result)

if hex_num == '0xa1b2c3d4':
    print('matched')
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.