#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2013
    Posts
    34
    Rep Power
    5

    Read binary by chunks of different size


    Hello to all,


    I'm trying to read a binary file in chunks, but the chunks have variable size and the size of each chunk has a known position.

    Main header = 16 bytes

    Then begin all the chunks and each chunk has a header of 12 bytes and after this header goes 3 bytes that say the chunk size.

    I currently have the code below that prints some values of first chunk, but I donīt know how to repeat this process for all the chunks.

    May somebody help me to accomplish this please.

    Code:
    FILENAME="file.bin"
    
    open(FILENAME, "rb") do |f|
        mainheader = f.read(16).unpack('H*')  
    	
    	puts mainheader
    	
    	puts "############### Chunk No. 1 ######################"
    	
            chunkheader = f.read(12)                                 
            chunksize = f.read(3).unpack('H*')[0].hex
    	data = f.read(chunksize).unpack('H*')
        
    	puts chunkheader.unpack('H*')
    	puts chunksize
    	puts data
                           
    
    end
    Thanks in advance
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2014
    Posts
    44
    Rep Power
    4
    Just surround:

    PHP Code:
    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 

    with loop
    :

    while 
    chunkheader z.read(16) do
      
    puts "############### Chunk ######################"
      
    chunksize z.read(4).unpack('H*')[0].hex
      data 
    z.read(chunksize).unpack('H*')

      
    puts chunkheader.unpack('H*')
      
    puts chunksize
      puts data 
    end 
    the loop above will be terminated as there is no more data in the file remained. Please note, that the snipped above is in general error-prone, since it expects the file to be not corrupted and will fail if last chunk header reports erroneous amount of bytes.

    But in your case it seems to be ok.

IMN logo majestic logo threadwatch logo seochat tools logo