Forum Moderators: coopster & phranque

Message Too Old, No Replies

How do you write this in Perl?

         

webguru

7:38 am on Apr 16, 2003 (gmt 0)

10+ Year Member



<?
$Word = "a";
$Code=Hexdec(Bin2hex($Word));
echo $Code;
?>

Fischerlaender

9:03 am on Apr 16, 2003 (gmt 0)

10+ Year Member



Try the unpack and hex functions.

perl -e '$a="ab"; $hex=unpack "H*",$a; print "$hex\n";'

This prints out "6162", because those are the Hex values of a and b. This should be the aquivalent of Bin2Hex.

perl -e 'print hex(6162)."\n";';

This gives "24930".

webguru

12:45 am on Apr 18, 2003 (gmt 0)

10+ Year Member



I have tried to compose two scripts and they got different result:

<?
$Word = "a";
$Code=Bin2hex($Word);
echo $Code;
?>

result 61

and
#!/usr/bin/perl
use CGI qw(:standard);
$string="a";
$string = unpack "H*",$string;
$string = hex($string);
print header();
print $string."<br>\n";

result 91

So, they are different!

ShawnR

7:58 am on Apr 19, 2003 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hi Webguru

Your first post had an additional bit of processing (a call to Hexdec()). If that has been removed from the php code, then to make the perl code equivalent, you should remove $string = hex($string); from the perl code.

Shawn

Fischerlaender

8:32 am on Apr 19, 2003 (gmt 0)

10+ Year Member



This was your initial PHP code:
<? 
$w="a";
$c=Hexdec(Bin2Hex($w));
echo $c;
?>

Result: 97
(Your "result 91" must be a typo.)

This is my Perl code:

$w="a"; 
$c=unpack("H*",$w);
$c=hex($c);
print $c;

Result: 97

Fischerlaender

8:34 am on Apr 19, 2003 (gmt 0)

10+ Year Member



BTW: If you're just interested in the transformation of a single character, then you should just use ord:
$w="a"; 
print ord($w);

This gives also 97.