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

2

1 Answer 1

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'>
Sign up to request clarification or add additional context in comments.

1 Comment

The problem with this is that b'0xff' has a length of 4, for my purposes I need the output to be exactly b'\xff'

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.