Ruby - Unpack irregular binary string


I have an irregular binary file that has been produced by an external program.

The beginning of the file looks like this


As you can see, it has a repetitive pattern:

  • String (unspecified length)
  • tab (\t)
  • 6 floats
  • Repeat

In the ASCII version the first three elements would constitute a line:

mct_terrain_material    2.814988e+01    1.279283e+01    0.000000e+00    0.000000e+00    0.000000e+00    -1.000000e+00
FrontColor  2.814988e+01    2.571460e+01    2.437201e+00    0.000000e+00    9.986295e-01    5.233596e-02

There is no newline in the binary version.

I know how to unpack strings with only one type. In that case I would do:


My first idea was to use binstring.split("\t") and then build one by one starting the unpacking from the second element, but I think that there should be a more elegant solution.

Any idea?

Show source
| ruby   | regex   | binaryfiles   | unpack   2016-06-02 16:06 1 Answers

Answers to Ruby - Unpack irregular binary string ( 1 )

  1. 2016-06-02 16:06

    Could you try something along the lines of:

    while string = file.gets("\t") # separator instead of \n
      binary =*4) # or whatever size of the float is
      floats = binary.unpack('F*') # or however you unpack this to array
      # do whatever with string and floats

Leave a reply to - Ruby - Unpack irregular binary string

◀ Go back