Hexadecimals (perl)

From HalfgeekKB
Revision as of 08:00, 3 April 2005 by 161.253.9.181 (talk)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Data string to hex

# Convert data string to hex
my $a = "ZYXWVUT";
my $ax = unpack('H*',$a);
$ax eq '5a595857565554'
   or die "ax=$ax";

# Each character always becomes two hex digits,
# even if the high half is 0
my $b = pack('C*',1,2,3,4,5,6,7,8);
my $bx = unpack('H*',$b);
$bx eq '0102030405060708'
    or die "bx=$bx";

Hex string to data

# Convert hex back to data string
my $cx = "5a595857565554";
my $c = pack('H*',$cx);
$c eq 'ZYXWVUT'
    or die "c=$c";

# That leading zero in hex is important
my $dx = '102030405060708';
my $d = pack('H*',$dx);
$d ne pack('C*',1,2,3,4,5,6,7,8)
    or die "Forgotten leading zero didn't matter";