#!/usr/bin/perl

# Filename: hex2bin.pl
# Author: Phil Smith, BroadOn Communications
# Date: 6/2/05

# converts an ascii hex file to ascii binary.  The intent is
# to produce a data file that can be read via the Verilog 
# $readmemb() PLI call.
#
# Hex file lines of the following form
#
#    \s*[0-9a-zA-Z]+
# 
# are translated to binary of the form
#
#    ([01][01][01][01]_)+  // <original input line>
#
# Note that the original hex lines are appended to the 
# converted binary lines as comments.
#
# Any hex file lines that do nat match the above form are 
# copied verbatim into the binary output file.
#
# To convert a binary file (X.raw) into ascii hex file
# (X.hex), execute the following sequence of commands --
#
# % cat X.raw | od -tx4 -w4 -v | cut -d" " -f2 -s | hex2bin.pl > X.hex
#

%bdigit = 
    qw/
    0 0000 
    1 0001 
    2 0010 
    3 0011 
    4 0100 
    5 0101 
    6 0110 
    7 0111
    8 1000 
    9 1001 
    a 1010 
    b 1011 
    c 1100 
    d 1101 
    e 1110 
    f 1111
    A 1010 
    B 1011 
    C 1100 
    D 1101 
    E 1110 
    F 1111
/;

while (<>) {
    $line = $_;

    if ( /^\s*([0-9a-fA-F]+)/ ) {
        $hdigits = $1;
        foreach (split //,$hdigits) {
            print "$bdigit{$_}_";
        }
        print "\t// $line";
    } else {
        print $line;
    }
}
