0

I'm trying to convert a string / int list to a .bin bytes format final file:

final_data = ['3247', '5146', '6971', '-8192', '8192', '11192']
final_data2 = [int(i) for i in final_data]
arr = bytes(final_data2)
with open("data.bin", "wb") as fh:
    fh.write(arr)

But I'm getting this error:

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

How to proceed knowing that I have negative numbers and numbers larger than 256 ?

1 Answer 1

1

You could go for something like this: The to_bytes() call transform each int to a binary representation.

final_data = ['3247', '5146', '6971', '-8192', '8192', '11192']

with open("data.bin", "wb") as fh:
    for i in final_data:
      fh.write(int(i).to_bytes(32, byteorder = 'big', signed = True))
Sign up to request clarification or add additional context in comments.

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.