Herong's Tutorial Notes on Perl - Part A
Dr. Herong Yang, Version 4.09

Input and Output in Binary Mode

Part:   1  2  

(Continued from previous part...)

Converting Binary Data to Hex Numbers - Bin2Hex.pl

As another example, I wrote Bin2Hex.pl to convert binary data to hex numbers:

#- Bin2Hex.pl
#- Copyright (c) 1995 by Dr. Herong Yang
#
   ($in, $out) = @ARGV;
   die "Missing input file name.\n" unless $in;
   die "Missing output file name.\n" unless $out;
   $byteCount = 0;
   open(IN, "< $in");
   binmode(IN);
   open(OUT, "> $out");
   while (read(IN,$b,32)) {
      $n = length($b);
      $byteCount += $n;
      $s = 2*$n;
      print (OUT unpack("H$s", $b), "\n");
   }
   close(IN);
   close(OUT);
   print "Number of bytes converted = $byteCount\n";
   exit;

Of course, I had to write Hex2Bin.pl to convert hex numbers back to binary data:

#- Hex2Bin.pl
#- Copyright (c) 1995 by Dr. Herong Yang
#
   ($in, $out) = @ARGV;
   die "Missing input file name.\n" unless $in;
   die "Missing output file name.\n" unless $out;
   $byteCount = 0;
   open(IN, "< $in");
   open(OUT, "> $out");
   binmode(OUT);
   while (<IN>) {
      chop;
      $s = length($_);
      $byteCount += $s/2;
      print (OUT pack("H$s", $_));
   }
   close(IN);
   close(OUT);
   print "Number of bytes converted = $byteCount\n";
   exit;

To test this program, I used the following commands:

>copy c:\winnt\system32\ping.exe ping.exe
        1 file(s) copied.

>Bin2Hex.pl ping.exe ping.hex
Number of bytes converted = 16144

>Hex2Bin.pl ping.hex ping_copy.exe
Number of bytes converted = 16144

>ping_copy localhost
Pinging localhost.herong.com [127.0.0.1] with 32 bytes of data:

Reply from 127.0.0.1: bytes=32 time<10ms TTL=128
Reply from 127.0.0.1: bytes=32 time<10ms TTL=128
Reply from 127.0.0.1: bytes=32 time<10ms TTL=128
Reply from 127.0.0.1: bytes=32 time<10ms TTL=128

Ping statistics for 127.0.0.1:
    Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 0ms, Maximum =  0ms, Average =  0ms

Part:   1  2  

Dr. Herong Yang, updated in 2006
Herong's Tutorial Notes on Perl - Part A - Input and Output in Binary Mode