4

I have an array of unsigned integers (32 bits) that I want to pack into a binary stream:

my @n = (4,8,15,16,23,42);
my $foo = join('', map(pack('I', $_), @n)); # Ugly, isn't?

$foo should contains this binary stream (depending on the endianness)

0000000 0000 0004 0000 0008 0000 000F 0000 0010
0000010 0000 0017 0000 002A

Then I would like to unpack the binary stream back to an array.

How do I properly do it with Perl and if possible with only built-in modules?

3
  • 2
    The variables $a and $b are reserved for use in sort blocks and it's considered bad practice to use them for anything else. Commented Sep 17, 2014 at 13:14
  • Good point! I will use $foo $bar instead :) Commented Sep 17, 2014 at 13:18
  • Removing the unnecessary parens would have helped too. join '', map pack('L', $_), @nums; Commented Sep 17, 2014 at 13:44

1 Answer 1

7

All you need is

my $packed = pack('I*', @nums);   # unsigned int (varies in size)
my $packed = pack('L*', @nums);   # uint32_t
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.