Perl pack integer

273 views Asked by At

Considering this value:

my $value = hex('0x12345678');

And I would like my hexdump to be like this (same bits order):

0000000 1234 5678

I used this method but it mixes up my value:

open(my $out, '>:raw', 'foo') or die "Unable to open: $!";     
print $out pack('l', $value);  # Test in little endian
print $out pack('l>', $value); # Test in big endian

Here's what I get:

0000000 5678 1234 3412 7856

How can I get the bits in order?

EDIT

So the problem might come from my hexdump, because I get the same output with the suggested answer.

$ perl -e 'print pack $_, 0x12345678 for qw( l> N )' | hexdump
0000000 3412 7856 3412 7856

I got the correct result with hexdump -C:

$ perl -e 'print pack $_, 0x12345678 for qw( l> N )' | hexdump -C
00000000  12 34 56 78 12 34 56 78                           |.4Vx.4Vx|

And I found the explanation here: hexdump confusion

1

There are 1 answers

6
choroba On BEST ANSWER

The 'l>' option works for me (note there's no call to hex, though). Also, N as the template works:

perl -e 'print pack $_, 0x12345678 for qw( l> N )' | xxd
0000000: 1234 5678 1234 5678