Search code examples
perl

Reading hex values from a file, writing binary value to another file


I have one, huge, single column file, that contains text strings that represent hex values, on each row. I want to read the values in the file and produce a corresponding file that contains the same values but in binary format.

#!/usr/bin/perl
use strict;
use warnings;

my $defaultfile = 'C:\Users\john\Desktop\input.txt';
my $mainfile ='C:\Users\john\Desktop\output.txt';

open( my $default_fh, "<:encoding(UTF-8)", $defaultfile ) or die $!;
open( my $main_fh,    ">", $mainfile )    or die $!;
while ( my $line = <$default_fh> ) {
    chomp $line;
    print {$main_fh} $line;
    print {$main_fh} "\n";
}
close $default_fh;
close $main_fh;

So far this has been my code. As I am new to Perl, can someone help me with that?

Example;

File1(in Hex): 
line 1 1C
line 2 0A
line 3 89
and so on 

File2(in Binary): 
line 1 00001110
line 2 00001010
line 3 10001001
and so on

Solution

  • Convert the input string to a numeric value with hex, then print as binary using %b. You would change your 1st print line to:

    printf {$main_fh} '%08b', hex $line;
    

    Self-contained example:

    use warnings;
    use strict;
    
    while (<DATA>) {
        chomp;
        printf "%08b\n", hex $_;
    }
    
    __DATA__
    1c
    0a
    89
    

    Output:

    00011100
    00001010
    10001001