Reputation: 2511
I have four bytes which I need to read as a long
.
When I read my file, I read the following bytes:
['\x10', '\xef', '\xf1', '\xea']
According to my file format description, these four bytes represent a long.
How would I convert these bytes to a long with Python?
Additionally: Would one use a similar method to convert 2 bytes into a Short?
Here is example code of how I read my file:
source = "test.whatever"
print "Loading file:", source;
data = []
f = open(source, "rb")
counter = 0;
#Let's load the data here:
try:
byte = f.read(1) #skip the first byte according to my file
while byte != "":
byte = f.read(1)
data.append(byte) #read every byte into an array to work on later
counter = counter + 1
finally:
f.close()
print "File loaded."
print counter
Upvotes: 1
Views: 2040
Reputation: 249303
import struct
struct.unpack('>l', ''.join(ss))
I chose to interpret it as big-endian, you need to decide that yourself and use <
instead if your data is little-endian.
If possible, use unpack_from()
to read the data directly from your file, instead of using an intermediate list-of-single-char-strings.
Upvotes: 3