secarica
secarica

Reputation: 619

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

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 the byte 0x5a, which I want to compare with a string that says '5a' (or '5A', case is not important). 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?

Upvotes: 1

Views: 102

Answers (2)

BrokenBenchmark
BrokenBenchmark

Reputation: 19252

You can use hex() to turn the integer into a hex string, and then you can 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

Upvotes: 2

jthulhu
jthulhu

Reputation: 8678

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'

Upvotes: 2

Related Questions