Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Re: Faster way to parse binary stream

by BrowserUk (Patriarch)
on Jun 19, 2007 at 19:50 UTC ( [id://622091]=note: print w/replies, xml ) Need Help??


in reply to Faster way to parse binary stream

If the entire string (after the first 'no of strings' byte) is made up length/string pairs, then (subject to using an unenbalmed version of Perl) let unpack take care of it. Ignore/skip the first byte and use the ()repeat pattern to deal with it. Eg:

$count = 3; $str1 = "First string"; $str2 = "Second string"; $str3 = "Third string"; $bytes = pack("C C A* C A* C A*", $count, length($str1), $str1, length($str2), $str2, length($str3), $str3);; print for unpack 'x(c/a*)*', $bytes;; First string Second string Third string

If there is other stuff following the strings, then you'll need to unpack the first byte and then generate the pattern:

$n = unpack 'C', $bytes;; print for unpack 'x (c/a*)' . $n, $bytes;; First string Second string Third string

Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.

Replies are listed 'Best First'.
Re^2: Faster way to parse binary stream
by ikegami (Patriarch) on Jun 19, 2007 at 20:29 UTC

    You can even combine the two calls to unpack:

    my @strings = unpack 'c/(c/a*)', $bytes;
Re^2: Faster way to parse binary stream
by Roy Johnson (Monsignor) on Jun 19, 2007 at 20:29 UTC
    I hadn't seen the slash template item before. To quote from the docs:

    The / template character allows packing and unpacking of strings where the packed structure contains a byte count followed by the string itself. You write length-item/string-item.

    Good solution, BrowserUK.


    Caution: Contents may have been coded under pressure.
      Thanks to all who replied - the "C/(C/A*)*" looks like the way to go :)

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://622091]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others browsing the Monastery: (4)
As of 2024-04-23 22:19 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found