Hexadecimal to Binary File Conversion Utility

V

Victor Hannak

This perl script is useful for creating binary files out of text files
containing hexadecimal values. I have found it useful for many a
simulation.

Vic

------------------------------- cut here

#!/usr/bin/perl

if ( @ARGV != 2 ) {

$0 =~ m%(.*)/(\w+)$%; # Separate script name into path and name
die "
Usage: $2 <hex_file> <binary_file>

Description: Takes a text file with hex bytes (pairs of two hex characters)
separated by spaces and converts it into a binary file.
Comments can be entered in the text file by preceding them
with a pound character. Newlines are ignored except to
mark the end of a comment.

Example Input File:

12 34 56 78 # These will be the first four bytes of the binary file
9A BC DE F0 # These will be the second four bytes of the binary file
12 34 56 78 # These will be the last four bytes of the binary file

Notes: Created by Victor Hannak on 2/20/2004.
Feel free to modify and reuse as needed.\n\n\n";

}

$HexFile = $ARGV[0];
$BinFile = $ARGV[1];

if ( ! -e $HexFile) {
die "\n\nERROR: $ARGV[1] is not a valid filename\n\n\n";
}

open(HEXFILE, $HexFile) || die "ERROR: Can't open $HexFile for reading: $!";
open(BINFILE, ">$BinFile") || die "ERROR: Can't open $BinFile for writing:
$!";
binmode BINFILE;
$BinString = "";

while (<HEXFILE>) {
chomp;
s/^\s+//;
s/\#.*$//;
s/\s+$//;
s/(\w\w)/hex $1/eg;
@array = split;
$BinString = $BinString . pack("C*",@array);
}

print BINFILE $BinString;

close HEXFILE;
close BINFILE;

------------------------------- cut here
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,011
Latest member
AjaUqq1950

Latest Threads

Top