http://www.perlmonks.org?node_id=622870

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

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.