bytes and characters - how to decode?

P

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

Thnx
-Neo
 
T

Tassilo v. Parseval

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
 

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. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top