I'm trying to read a binary file that has chunks of variable size. The size of each chunk is located in a fix position at the beginning of each chunk.
The file is composed like this:
- Main header = first 20 bytes of the file
- After Main header come all the chunks.
- Each chunk has a header of 16 bytes
- The 4 bytes after chunk header represent the size of the chunk.
I currently have the code below that extracts main header and chunk header, size and data for first chunk, but I'm quite of novice, and I'm stuck in how to repeat this process for all the chunks.
May somebody help with my case please.
FILENAME="file.bin"
open(FILENAME, "rb") do |z|
mainheader = z.read(20).unpack('H*')
puts mainheader
puts "############### Chunk No. 1 ######################"
chunkheader = z.read(16)
chunksize = z.read(4).unpack('H*')[0].hex
data = z.read(chunksize).unpack('H*')
puts chunkheader.unpack('H*')
puts chunksize
puts data
end