2

I need to convert int list into a byte string but I don't know how. I can't use bytes() because the values are too large.

bytes([152710136, 76354857, 38177353, 2252736081, 1126368238])

I get this error:

ValueError: bytes must be in range(0, 256)

The expected value is:

b'\xc4\xb7\x86\x17\xcd'
3
  • Specify what "byte string" means. Ascii-coded bytes as textual representation? Commented Jan 21, 2018 at 16:50
  • 1
    What is the expected output? Commented Jan 21, 2018 at 16:50
  • 1
    If the values are less than 256 you can use bytes(list) and it will give you the result. Commented Jan 21, 2018 at 16:56

2 Answers 2

5

You can use .to_bytes to return an array of bytes representing an integer. Note: This works only in python 3.1 and above.

For example:

>>> (1024).to_bytes(2, byteorder='big')
b'\x04\x00'
Sign up to request clarification or add additional context in comments.

Comments

1

I needed to use struct.unpack() and it accepts a byte string rather than a list of ints. I was able to convert my list of ints to a byte string with:

bytearray(mylist)

Tested on python 2.7.

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.