ruby - Unpack binary file containing repetitions -


i have binary file stores numbers repetition of 2 unsigned 32-bit integers followed 1 unsigned 8-bit integer. read file string , want decode array of arrays, each containing 3 numbers. this:

file.open("file", "r"){|f| f.read.unpack("llc")} 

however, not work, since handles first 3 numbers in file. doesn't work:

file.open("file", "r"){|f| f.read.unpack("llc*")} 

since parses rest of file 8-bit integers, , not create array of arrays. less critical since can hand, must repeat llc pattern.

try following:

file.open("file", "rb") { |f|   result = []   while true     data = f.read(9)     break unless data && data.length == 9     result << data.unpack('llc')   end   result } 

btw, use binary mode (rb).


alternative:

file.open("file", "rb") { |f|   result = f.read.chars.each_slice(9).map { |data|     data.join.unpack("llc")   } } 

"\x01\x00\x00\x00\x02\x00\x00\x00\x03\x04\x00\x00\x00\x05\x00\x00\x00\x06".chars.each_slice(9).map { |chs| chs.join.unpack("llc") } # => [[1, 2, 3], [4, 5, 6]] 

Comments

Popular posts from this blog

html - How to style widget with post count different than without post count -

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

javascript - storing input from prompt in array and displaying the array -