Hello Monks,

I have a binary file that looks like the following in a hex editor(these are the first 8 bytes):

02 00 00 00 f7 ff f4 ff ....

What I would like to do is convert every 2 bytes into an ASCII string that I can then write out to a new file. So for the above example, I want my output file to look like this (bytes flipped due to endianness issues):

0x0002, 0x0000, 0xfff7, 0xfff4 What I have found so far is that I need to set the filehandle to binary mode using binmode() after I open it, and then also use ord() to convert a binary value to its ascii equivalent. The problem I have right now is trying to group every set of 2 binary bytes into 4 hex digits but reversed for the endianness reason. My code so far:

$ctr = 0; # get first argument, i.e filename $in_filename = shift; print "You chose input <$in_filename>\n"; $out_filename = shift; print "You chose output <$out_filename>\n"; open(INFILE, $in_filename) or die "can't open input file: $!"; #set infile to binary mode binmode(INFILE); open(OUTFILE, ">$out_filename") or die "can't open output file: $!"; while(<INFILE>) { @samples = split(//,$_); foreach $byte (@samples) { print OUTFILE "0x".sprintf("%02hx",ord($byte)).", "; $ctr += 1; if (($ctr % 8) == 0) { print OUTFILE "\n"; $ctr = 0; } } }
As output this will give me:

 0x02,0x00,0x00,0x00,0xf7,0xff,0xf4,0xff

Any suggestions on how to get the behavior I would like? Furthermore, when I call split on one line of the binary file, will it split the line into individual bytes? This is what it appears to be doing, but then how does ord work exactly? If it sees a binary value of ff what does it convert that to? Thanks.


In reply to Convert binary file to ascii by richz

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.