1

With Python, given an offset say 250 bytes, how would I jump to this position in a file and store a 32bit binary value?

My issue is read() returns a string and I'm not sure if I'm able to properly advance to the valid offset having done that. Also, experimenting with struct.unpack() it's demanding a length equivalent to the specified format. How do I grab only the immediate following data according to what's expected of the specified format? And what's the format for a 32bit int? Ex. I wrote a string >32 characters and thought I could grab the initial 32 bits and store them as a single 32 bit int by using '<qqqq', this was incorrect needless to say.

tshepang
  • 12,111
  • 21
  • 91
  • 136
John Smith
  • 283
  • 2
  • 19
  • possible duplicate of this: http://stackoverflow.com/questions/2576712/using-python-how-can-i-read-the-bits-in-a-byte – jean-loup Jul 28 '14 at 15:29

1 Answers1

3
with open("input.bin","rb") as f:
    f.seek(250) #offset 
    print struct.unpack("<l",f.read(4)) #grabs one little endian 32 bit long 

if you wanted 4, 32 bit ints you would use

print struct.unpack("<llll",f.read(16))

if you just want to grab the next 32bit int

print struct.unpack_from("<l",f)[0]
Joran Beasley
  • 110,522
  • 12
  • 160
  • 179