nowox
nowox

Reputation: 29096

Pack/unpack array of binary data

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?

Upvotes: 4

Views: 1359

Answers (1)

ikegami
ikegami

Reputation: 385789

All you need is

my $packed = pack('I*', @nums);   # unsigned int (varies in size)
my $packed = pack('L*', @nums);   # uint32_t

Upvotes: 7

Related Questions