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.
my $num=0x5514ddb7;
my $i = unpack('N', pack('V',$num));
printf("0x%x\n", $i);
But are you sure you want to do this? It's 32-bit-specific. The question begs for a "why do you ask?" in order to suggest something better than whatever it is you're trying to solve.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With