bytes and characters - how to decode?

Discussion in 'Perl Misc' started by Panchal V, Aug 21, 2004.

  1. Panchal V

    Panchal V Guest

    I have to process a packet, it looks like this :
    $str = "\0\0\0\2\0\0\0\1\2\x41\x42";

    version -> 2 (first 4 octects)
    type -> 1 (next 4 octects)
    length -> 1 (next 1 octect)
    data -> 'AB' (next 2 octect)

    how do i decode this packet??? i want first 4 bytes to be treated as
    an Unsigned Integer i.e. version is 2 here in this case...

    I tried
    $str =~ m/(.{4})(.{4})(.)/;
    $version = pack "I", $1;

    but doesn't help... HOW CAN I extract fields values???

    Panchal V, Aug 21, 2004
    1. Advertisements

  2. Also sprach Panchal V:
    There is no need for the pattern match when you use unpack() properly.
    It can return a list of values so the unpacking can be done in one go.
    Assuming the above record is two unsigned integers, followed by a length
    indicator being an unsigned char and finally that many characters, you'd
    do it that way:

    my ($ver, $type, $data) = unpack "IIC/a", $str;

    Note that the 'I' template specifies integers in the native byteorder
    and native width of your machine. Since "\0\0\0\2" only represents the
    value 2 on big-endian machines, it is not portable to machines with a
    different byteorder. Therefore you better use 'N':

    my ($ver, $type, $data) = unpack "NNC/a", $str;

    Tassilo v. Parseval, Aug 21, 2004
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.