# hex to binary conversion

#### Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

•  Subject
• Author
• Posted on
Hi.
I can convert "414243" to "ABC" using awk (see below) but wonder if there's
a simpler way of doing it in Perl.
perl -e 'printf "%c", hex("41")'            # works for a single
hard-coded 2-character string

How do I do it for lines of arbitrary length?

My awk equivalent is:

awk 'BEGIN {for (i=0;i<=15;i++){

for (j=0;j<=15;j++)

}

}

{

for (i=1;i<=length(\$0);i+=2) {

x=tolower(substr(\$0,i,1))

y=tolower(substr(\$0,i+1,1))

printf "%c",a[x y]

}

print ""

}'

TIA.

Jeffrey

## Re: hex to binary conversion

Jeffrey Ross wrote:

....
> I can convert "414243" to "ABC" using awk (see below) but wonder if there's
> a simpler way of doing it in Perl.
>         perl -e 'printf "%c", hex("41")'            # works for a single
> hard-coded 2-character string
>
> How do I do it for lines of arbitrary length?
>
> My awk equivalent is:
....
> TIA.

Try:

use strict;
use warnings;
my \$string='414243';
\$string=~s/([\da-f])/chr(hex(\$1))/egi;
print \$string;
>
> Jeffrey

--
Bob Walton
Email: http://bwalton.com/cgi-bin/emailbob.pl

## Re: hex to binary conversion

> Jeffrey Ross wrote:
>
> ...
> > I can convert "414243" to "ABC" using awk (see below) but wonder if
there's
> > a simpler way of doing it in Perl.
> >         perl -e 'printf "%c", hex("41")'            # works for a single
> > hard-coded 2-character string
> >
> > How do I do it for lines of arbitrary length?
> >
> > My awk equivalent is:
> ...
> > TIA.
>
> Try:
>
> use strict;
> use warnings;
> my \$string='414243';
> \$string=~s/([\da-f])/chr(hex(\$1))/egi;
> print \$string;
> >
> > Jeffrey
>
> --
> Bob Walton

Thanks, Bob.
That's scary (but the sort of thing I wanted)!
Jeffrey.

## Re: hex to binary conversion

Jeffrey Ross wrote:
> I can convert "414243" to "ABC" using awk (see below) but wonder if there's
> a simpler way of doing it in Perl.
>         perl -e 'printf "%c", hex("41")'            # works for a single
> hard-coded 2-character string
>
> How do I do it for lines of arbitrary length?

\$ perl -le' \$_ =  pack "H*", "414243"; print '
ABC

John
--
use Perl;
program
fulfillment

## Re: hex to binary conversion

>How do I do it for lines of arbitrary length?

Here's a non-scary perl way:

%h2b = (0 => "0000", 1 => "0001", 2 => "0010", 3 => "0011",
4 => "0100", 5 => "0101", 6 => "0110", 7 => "0111",
8 => "1000", 9 => "1001", a => "1010", b => "1011",
c => "1100", d => "1101", e => "1110", f => "1111",
);

\$hex = "414243";
(\$binary = \$hex) =~ s/(.)/\$h2b{lc \$1}/g;
print \$binary, "\n";

Hope this helps.