Reputation: 2801
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?
Upvotes: 1
Views: 1837
Reputation: 35059
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.
Upvotes: 1
Reputation: 796
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?
Upvotes: 0