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???

    Thnx
    -Neo
     
    Panchal V, Aug 21, 2004
    #1
    1. Advertising

  2. Also sprach Panchal V:

    > 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???


    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
    --
    $_=q#",}])!JAPH!qq(tsuJ[{@"tnirp}3..0}_$;//::niam/s~=)]3[))_$-3(rellac(=_$({
    pam{rekcahbus})(rekcah{lrePbus})(lreP{rehtonabus})!JAPH!qq(rehtona{tsuJbus#;
    $_=reverse,s+(?<=sub).+q#q!'"qq.\t$&."'!#+sexisexiixesixeseg;y~\n~~dddd;eval
     
    Tassilo v. Parseval, Aug 21, 2004
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. F. GEIGER
    Replies:
    0
    Views:
    1,592
    F. GEIGER
    May 27, 2005
  2. BogusException
    Replies:
    7
    Views:
    339
  3. George2
    Replies:
    1
    Views:
    894
    Victor Bazarov
    Jan 9, 2008
  4. Roy H. Han
    Replies:
    18
    Views:
    2,359
    Gabriel Genellina
    Feb 25, 2009
  5. Joe
    Replies:
    9
    Views:
    2,139
Loading...

Share This Page