Question

I have one binary file and I want to read this file like first four bytes then next 5 bytes then next 3 bytes till file ends.

I am able to read file using each_byte but I want to categorize all these bytes in groups in sequence they are stored in file.

I am able to read this using following lines but dont know how to read in fixed sized blocks with continutation.

File.open('myfile','rb') do |file|
file.each_byte {|ch| print "#{ch.chr}:#{ch}\t"}

end

Was it helpful?

Solution

I'm not sure I understand but maybe something like:

file.read.scan(/(.{4})(.{5})(.{3})/).each do |a,b,c|
    puts "first 4 bytes: #{a}"
    puts "bytes 5 to 10: #{b}"
    puts "3 more bytes: #{c}"
end

OTHER TIPS

It's not really fast, but it's ruby :-)

file.each_byte.slice_before({pattern: [4,5,3].cycle, left: 0}) do |ele, state|
  if state[:left] == 0
    state[:left] = state[:pattern].next
    true
  else
    state[:left] -= 1
    false
  end
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top