Hexadecimal to Binary File Conversion Utility

Discussion in 'VHDL' started by Victor Hannak, Feb 20, 2004.

  1. 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
     
    Victor Hannak, Feb 20, 2004
    #1
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Bengt Richter

    Hexadecimal Conversion in Python

    Bengt Richter, Nov 2, 2005, in forum: Python
    Replies:
    10
    Views:
    51,221
    Peter Hansen
    Nov 2, 2005
  2. lei
    Replies:
    10
    Views:
    778
    Don Roby
    Dec 30, 2006
  3. hexadecimal to float conversion

    , Aug 19, 2005, in forum: C Programming
    Replies:
    4
    Views:
    1,727
    Keith Thompson
    Aug 20, 2005
  4. Shivani
    Replies:
    3
    Views:
    299
    Joe Wright
    Sep 7, 2005
  5. Deepu

    Binary to Hexadecimal conversion

    Deepu, Dec 15, 2007, in forum: Perl Misc
    Replies:
    5
    Views:
    183
Loading...

Share This Page