Ruby String # unzip

I have a packaged string of three lines, which is structured so that I have an integer specifying the byte length of the next element, and then the bytes of the element, and then the next byte element, etc., as if someone did something

[a.bytesize, a, b.bytesize, b, c.bytesize, c].pack("na*na*na*")

How can I unpack this correctly in a simple way? Perl solution for this problem:

my($a, $b, $c) = unpack("(n/a*)3", $data)

For ruby, which apparently does not support "/" and parentheses in unpacking, I use something like:

vals = []
3.times do
  size = data.unpack("n").first
  data.slice!(0, 2)
  vals << data.unpack("a#{size}").first
  data.slice!(0, size)
end

Is there an easier way to do this?

+5
source share
3 answers

IMHO it is not as simple as in PERL , but it is some solution that I can offer.

unpacked = []
a, b, c = *unpacked << data.slice!(0, data.slice!(0, 2).unpack('S>').first) \
           until data.empty? 
+1
source

, Perl ( , , Ruby pack/unpack), :

vals = []
until data.empty?
  vals << data.slice!(0, data.slice!(0,2).unpack('n').first.to_i).unpack("a*").first
end
0

If you need serious binary processing, there is a gem: http://bindata.rubyforge.org/ I think you should use it instead of faking unpacked idle loops.

Of course, you can submit a request for a function and wait for its implementation, but I suggest you use the bindata pearl instead, which is a much more reliable IMO solution.

0
source

All Articles