1

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?

6
  • Didn't you delete a very long post with a vast amounts of comments earlier that was asking this? Commented Jan 30, 2015 at 0:14
  • 1
    bytes('a','ASCII') ? Commented Jan 30, 2015 at 0:14
  • @JonClements I did a very bad job asking what I meant to ask in that post. Commented Jan 30, 2015 at 0:23
  • @Startec then that's why you could have edited your previous post to clarify - having kept the comments and context in place, so more information is available as to what you're trying to achieve and what other people have already spent their time prompting you towards - rather than just deleting it and re-posting. Commented Jan 30, 2015 at 0:25
  • @JonClements, I wish I would have done that. The post (due to my own poor writing) was closed and I think my edits permanently messed it up. Believe me, I learned a lot about SO (and bytes) from this. Commented Jan 30, 2015 at 0:30

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Your comment helps me a lot. I am aware that 97 == 0x61, however, what lead to my confusion is the following b'a' == bytes([97]) = True but b'a' == b'\x61 = False. I wanted to make sure I had the hex value representing the integer 97, not the byte with a hex value of 97, which would be an integer of 151. Sorry, that sounds unclear, but do you understand my confusion?
b'a' == b'\x61' returns True for me. Still, I think I understand what you were confused about.
Also, just correcting your terminology - an "integer" is a number which can be represented in (among infinite other bases!) base-10 ("decimal") or base-16 ("hex"). So 151 is an integer, and so is 0x61, and so is 0b010110, etc. You may avoid a bit of confusion in later questions by changing your language a little :)
0
"\x67".encode("hex") 

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.