Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I start reading at an offset in binary data?

I have a C-like struct like this:

SomeStruct << BinData::Record
endian :little

uint32 :offsetOfName
uint32 :offsetOfLastname
#...
uint32 :lenVars
struct :Person, :length => :lenVars
    string :name
    string :lname
    #...
end

I have a bunch of offsets and lengths before :Person. All the offsets and lengths describe the data within the :Person struct.

How can I start reading data at a specified offset, for the given length, or until the next offset?

like image 234
omninonsense Avatar asked Jun 12 '11 19:06

omninonsense


People also ask

How do you find the offset in binary?

Offset binary: subtract half the largest possible number to get the value represented. I.e., you use half the largest number as the "zero" of the scale. For four bits: 2's Complement: negative integer is the complement of the positive integer plus one.

What is offset in binary file?

The offset indicates the number of bytes forward or backward from the base. For a binary file, the positionfile() function always positions the file to the beginning of a record. If you specify the offset clause, 4GL adjusts the file position to the beginning of the record containing the specified byte number.

How to read binary data file in matlab?

A = fread( fileID ) reads data from an open binary file into column vector A and positions the file pointer at the end-of-file marker. The binary file is indicated by the file identifier, fileID . Use fopen to open the file and obtain the fileID value. When you finish reading, close the file by calling fclose(fileID) .


1 Answers

Seek to offset 1234 and then read 32 bytes into String s:

open 'some-binary-file', 'r' do |f|
  f.seek 1234
  s = f.read 32
  # tho in your case, something like:
  o = aBinData_object.read f
  p s
end

Update: It looks like BinData understands records that encode the lengths of their own fields, but I doubt if there is any way to make it seek for you, unless you are willing to essentially encode dummy fields the size of the seeked-over space, and then ignore forever the data that it's skipping.

I suspect that a good solution will involve an explicit seek and then someBinDataObject.read(f) to get the record.

like image 147
DigitalRoss Avatar answered Oct 16 '22 01:10

DigitalRoss