Perl Tutorials - Herong's Tutorial Examples - v6.02, by Herong Yang
Bin2Hex.pl - Converting Binary Data to Hex Numbers
This section provides a tutorial example on how to convert binary data file to hex numbers - Bin2Hex.pl.
As another example, I wrote Bin2Hex.pl to convert binary data to hex numbers:
#- Bin2Hex.pl #- Copyright (c) HerongYang.com. All Rights Reserved. # ($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) HerongYang.com. All Rights Reserved. # ($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:
herong> copy c:\windows\system32\find.exe find.exe 1 file(s) copied. herong> Bin2Hex.pl find.exe find.hex Number of bytes converted = 17408 herong> hex2Bin.pl find.hex find_copy.exe Number of bytes converted = 17408 herong> dir find*.* 17,408 find.exe 35,904 find.hex 17,408 find_copy.exe herong> find_copy.exe /? Searches for a text string in a file or files. FIND [/V] [/C] [/N] [/I] [/OFF[LINE]] "string" ... ...
Table of Contents
Data Types: Values and Variables
Expressions, Operations and Simple Statements
Name Spaces and Perl Module Files
Hard References - Addresses of Memory Objects
Objects (or References) and Classes (or Packages)
Typeglob and Importing Identifiers from Other Packages
String Built-in Functions and Performance
File Handles and Data Input/Output
binmode() - Opening Files for Binary Input
binmode() - Opening Files for Binary Output
Copy.pl - Copying Binary Files
►Bin2Hex.pl - Converting Binary Data to Hex Numbers
Open Directories and Read File Names
File System Functions and Operations
Socket Communication Over the Internet
XML::Simple Module - XML Parser and Generator
SOAP::Lite - SOAP Server-Client Communication Module
Perl Programs as IIS Server CGI Scripts
CGI (Common Gateway Interface)
XML-RPC - Remote Procedure Call with XML and HTTP
RPC::XML - Perl Implementation of XML-RPC
Integrating Perl with Apache Web Server
CGI.pm Module for Building Web Pages
LWP::UserAgent and Web Site Testing
Converting Perl Script to Executable Binary