tags:

views:

64

answers:

4

Hi, I'am trying to convert the variable $num into its reverse byte order and print it out. This is what I have done so far:

my $num=0x5514ddb7;
my $s=pack('I!',$num);
print "$s\n";

He prints it out as some non-printable characters and in a hex editor it looks right, but how can I get it readable on the console?

Already tried

 print sprintf("%#x\n",$s);

but he complains about an non-numeric argument, so I think pack returns a string. Any ideas how can I print out `0xb7dd1455 on the console, based on $num?

+6  A: 

You need to use unpack:

my $num=0x5514ddb7;
my $s=pack('I<!',$num);

my $x=unpack('I>!',$s);
printf("%#x\n",$x);
Kilian Foth
Note 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.
Michael Carman
+1  A: 
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.

Liudvikas Bukys
+1  A: 

As a mostly-C programmer who dabbles in perl, my immediate instincts are to slice and dice with bitwise operators:

$n2 = ($num & 0xff) <<24
    | ($num & 0xff00) <<8
    | ($num & 0xff0000) >>8
    | ($num & 0xff000000) >>24 ;

But, this being perl, there are undoubtedly many ways to achieve the same result, and there's probably a good perl idiom for this.

crazyscot
+2  A: 

You need to use CORE::unpack() "H" (capital H):

H   A hex string (high nybble first).

my $num=0x5514ddb7;
my $s=pack('I!',$num);
print unpack ("H*", "$s") . "\n"; # b7dd1455
Evan Carroll