Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print a variable in reversed byte order?

Tags:

perl

pack

unpack

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?

like image 797
jth Avatar asked Dec 17 '22 00:12

jth


2 Answers

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.

like image 97
Kilian Foth Avatar answered Dec 28 '22 22:12

Kilian Foth


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.

like image 43
Liudvikas Bukys Avatar answered Dec 28 '22 23:12

Liudvikas Bukys