1

I am trying to read binary file into a list of bytes. I was looking into this thread but it only gives me an array of characters.

How do I convert string characters into a list?

More or less what I want is this:

with open("decompressed_data.bin", mode='rb') as file:
    fileContent = file.read()
myStrList = list(fileContent)
# then convert this to a list of integers directly.
myIntList = convertToIntList(myStrList)

Is there a way to convert this list of characters into a list of integers without looping through every character?

Better yet, can I read the binary file direct into a list of integers the Python way?

2
  • What python version? 2 or 3? Commented Apr 29, 2017 at 2:23
  • 1
    Does this help at all? stackoverflow.com/questions/22229229/… Commented Apr 29, 2017 at 2:28

2 Answers 2

1

Python 3s updated open, available as io.open in Python 2.7, will do this directly. Although it may be printed resembling a character string, the object returned by read on a binary file is a bytes object, which behaves as a sequence of integers. You can see this if you print the element at a particular index, or by noticing it yields ints when you iterate over it.

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

Comments

0

In python, you have the binascii module in the standard library. For example:

binascii.hexlify(data)

return the hexadecimal representation of the binary data. that is, each byte gets converted into a two-digit hex integer representation. Does that help you out?

1 Comment

that will do it.

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.