2

I want to take an integer, that will be between 0 and 255, convert that to a hex string eg. '\xff' and then cast that to bytes to end up with b'\xff'. I had assumed that the following would work.

data_num = 255
data = chr(data_num)
data_byte = data.encode()

Any help would be appreciated

  • What have you tried to achieve your wanted results? What has your research concerning your problem shown? Can you provide code of your tries? [How do I ask a good question](https://stackoverflow.com/help/how-to-ask), [How much research effort is expected](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users) and [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) might be helpful to improve your question. – Geshode Jan 12 '18 at 13:12
  • I found the answer to this here: [link](https://stackoverflow.com/questions/21017698/converting-int-to-bytes-in-python-3) – Christopher Ryan Jan 14 '18 at 11:52

1 Answers1

2

Did you consider using the built-in hex function?

data = hex(255)
data = data.encode()
print(data, type(data))

Output:

b'0xff' <class 'bytes'>
Sqoshu
  • 944
  • 2
  • 9
  • 16