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

I have a string of hexadecimal numbers like

$a = '9b23b4b322b0da70';

and I want to convert it to a binary string. Is there a simple way to do this using pack() or vec()? currently I am thinking of splitting the string every two characters, and doing chr() on each of them, but I think this is probably not the best way, is it?

Replies are listed 'Best First'.
Re: packing hex
by rob_au (Abbot) on Dec 30, 2003 at 08:54 UTC
Re: packing hex
by Taulmarill (Deacon) on Dec 30, 2003 at 09:00 UTC
    $hex = pack ( "H*", $a ); $bin = unpack ( "B*", $hex ); print "$bin\n";
Re: packing hex
by davido (Cardinal) on Dec 30, 2003 at 17:05 UTC
    The tutorial that really helped me with pack and unpack the most was from Perl's POD: perlpacktut. It has a lot of great examples, and a pace that I found interesting but not overwhelming at first.

    Update: rob_au mentioned that perlpacktut is only available in Perl 5.8.0 or later. So for those who are still using pre 5.8.0 Perls, you may have to use http://www.perldoc.com to read perlpacktut.

    Hope this helps!


    Dave