Startec
Startec

Reputation: 13206

How to convert Python ASCII value to it's hexidecimal value (in bytes)

The ASCII value a has an integer value of 97 and a Hex value of 61

Going between its integer value of 97and ASCII representation (with ord and chr) is easy, however, I would like to convert the string to a bytes object with its hex value of 61 I think this would look like b'a' or bx\67

Additionally, how can I then convert the bytes object back into the integer value?

Upvotes: 1

Views: 114

Answers (2)

Joran Beasley
Joran Beasley

Reputation: 113988

"\x67".encode("hex") 

but I dont think you can do that in python 3 I think its more like

codecs.encode("\x67","hex") #maybe??

Upvotes: 0

Blorgbeard
Blorgbeard

Reputation: 103467

Is this what you want?

>>> b = bytes('a', 'ascii')
>>> b
b'a'
>>> b[0]
97

Your distinction between hex and decimal seems odd. Are you aware that 97 is exactly the same in memory as 0x61? A number does not have a base - only a representation of a number has a base. So it doesn't make sense to talk about a bytes object containing hex values as opposed to decimal values.

Upvotes: 1

Related Questions