Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Fellow Monks
I know that I can open a binary file using binmode, but how can I get access to the contents of that binary file as hexadecimal ?
Can I then, using perl, output that hex back into a binary file again.
If somebody could provide a snippet that would be helpful

Thanks.
Jonathan
  • Comment on open a binary file for hexadecimal manipulation

Replies are listed 'Best First'.
Re: open a binary file for hexadecimal manipulation
by mscharrer (Hermit) on Apr 22, 2008 at 10:54 UTC
    binmode is only used for encoding purposes, in case of ASCII text file (i.e. non-UTF8 or similar) it mostly only used to make sure that the line endings a not converted from Windows (CRLF) to Unix (LF) or Mac (CR) format or the other way around, which would corrupt a "binary" file. (Note: Actually all files are "binary", ASCII text files just have a simple "binary" format: 1 byte => 1 letter.) AFIK under Unix/Linux binmode doesn't normally do anything, it's added to make the script working prober Windows.

    You can convert binary strings to hexadezimal representation (i.e. text strings) and back using the Perl functions pack() and unpack(). There are a little confusing - I personally have problems to remember which does which way conversation - but very powerful. See perldoc for the details and you will definitely find a tutorial on the web how to use it.

    The code should look like this (untested):

    open(IN, '<', $ifilename); binmode(IN); while (!eof IN) { read(IN, my $binstring, $length); my $hexstring = unpack("...", $binstring); } [...] my $newbin = pack("...", $hexstring);

    Please note that pack() awaits a list of arguments...

    Update:
    See this tutorial. Direct at the start it shows how to do bin2hex and hex2bin!

Re: open a binary file for hexadecimal manipulation
by tachyon-II (Chaplain) on Apr 22, 2008 at 11:06 UTC

    Are you sure you don't actually want a hex editor? You can manipulate binary directly with perl. Hex is just human readable binary and if you plan on programatically manipulating it why bother converting to and from a human readable form? You may find Pack/Unpack Tutorial (aka How the System Stores Data) useful, especially if you have structured binary data.

Re: open a binary file for hexadecimal manipulation
by Anonymous Monk on Apr 22, 2008 at 10:40 UTC
    warn unpack 'H*', 'Hi'; warn pack 'H*', unpack 'H*', 'Hi';