1. 程式人生 > >Perl實現十進位制和十六進位制的轉換

Perl實現十進位制和十六進位制的轉換

從十進位制轉為十六進位制:

vim d2h.pl

#!/usr/bin/perl
# Convert list of decimal numbers into hex


for ($i=0;$i<@ARGV;$i++){
          printf("%d\t=0x%x\n",$ARGV[$i],$ARGV[$i]);
    }
~

chmod +x d2h.pl

$ ./d2h.pl 100 500 751
100     =0x64
500     =0x1f4
751     =0x2ef

同樣的,將十六進位制轉換為十進位制:

#!/usr/bin/perl
# Convert list of hex numbers into decimal

  for($i=0;$i<@ARGV;$i++) {
        $val=hex($ARGV[$i]);
        printf("0x%x=%d\n",$val,$val);

      }
$ ./h2d.pl 64 1f4 2ef
0x64=100
0x1f4=500
0x2ef=751
輸入引數時的值若寫成0x64這般形式也可得到相同結果。