Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pack an int as 32 bits big endian in Perl?

Consider this snippet:

use strict;
use warnings;

my $data = "1";
my $packed = pack("I",$data);
open(my $file,">","test.bin") || die "error $!\n";
binmode $file;
print $file $packed;

The thing is, trying to read it from another language, this appears to be little endian. Is there any template argument that allows me to write it as big endian? I'd like to avoid doing extra work when reading.

like image 314
Geo Avatar asked Feb 13 '10 23:02

Geo


2 Answers

Consider using the "N" template with pack:

http://perldoc.perl.org/functions/pack.html

like image 171
Tim Avatar answered Sep 18 '22 22:09

Tim


The solution is the N template.

my $packed = pack "N", $data;

See the pack documentation for a list of all pack options.

like image 45
Leon Timmermans Avatar answered Sep 20 '22 22:09

Leon Timmermans