I'm trying to convert the variable $num
into its reverse byte order and print it out:
my $num = 0x5514ddb7;
my $s = pack('I!',$num);
print "$s\n";
It's printing as some non-printable characters and in a hex editor it looks right, but how can I get it readable on the console? I already tried this:
print sprintf("%#x\n",$s);
This makes perl complain about a non-numeric argument, so I think pack
returns a string. Any ideas how can I print out 0xb7dd1455
on the console, based on $num
?
You need to use unpack
:
my $num = 0x5514ddb7;
my $s = pack('I<!',$num);
my $x = unpack('I>!',$s);
printf("%#x\n",$x);
Comment from Michael Carman: Be aware that byte-order modifiers (<
and >
) require Perl v5.10+. For older versions of Perl you'd have to use the N
and V
templates instead.