Home > other >  How to compare a hex byte with its literal (visual) representation in Python?
How to compare a hex byte with its literal (visual) representation in Python?

Time:04-26

I want to compare two entities, one being an int as a single byte and the other a str which is the ASCII code of the visual representation (visual reading) of that byte (not its ASCII value).

For example: I have byte 0x5a which I want to compare with a pure text that says '5a' (or '5A', case is unimportant) as when I speak or I read this in a book. I don't need to compare the byte versus the 'Z' ASCII character, which in my case would be a different thing.

How can I do that? Could be I am in a middle of a logical trap and I don't know how to search for a proper question or similar case.

CodePudding user response:

There are functions that allow you to transform numbers into their string representation, in certain basis. In your case, hex should do the trick. For example:

>>> hex(0x5a)
'0x5a'
>>> hex(0x5a)[2:] # get rid of `0x` if you don't want it
'5a'

CodePudding user response:

You can use hex() to turn the integer into a hex string, and then you slice off the first two characters using string slicing to remove the leading 0x:

lhs = 90
rhs = "5a"

print(hex(lhs)[2:] == rhs)

This outputs:

True
  • Related