Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 869
nowox Avatar asked Mar 19 '23 11:03

nowox


1 Answers

All you need is

my $packed = pack('I*', @nums);   # unsigned int (varies in size)
my $packed = pack('L*', @nums);   # uint32_t
like image 161
ikegami Avatar answered Mar 27 '23 05:03

ikegami