in reply to hex to bin

The docs for hex would point you at sprintf

my $bin = sprintf "%b", hex $hex;
To go the other direction requires you to do a little work. Perl doesn't come with a binary2decimal (or hex) converter, but you can write your own easily:
sub bin2dec { my @bits = reverse split '', shift; my $num = 0; for( my $i=0; $#bits >= $i; ++$i ) { $num += 2 ** $i if $bits[$i] } return $num } my $hex = sprintf "%x", bin2dec( $bin )

Replies are listed 'Best First'.
Re: Re: hex to bin
by merlyn (Sage) on Mar 09, 2001 at 08:47 UTC
    That's not bin2dec, that's bin2num, unless you're running Perl on a machine that is using BCD internally.

    Perl handles "num2dec" and "dec2num" so trivially that people sometimes get confused into believing that the numbers are stored as decimal internally. They're not.

    -- Randal L. Schwartz, Perl hacker

      Yes. Of course, Perl programmers enjoy that level of abstraction. Not worrying (too much) about how things are really stored makes it easier to focus on the important stuff... like algorithms. Thanks for your comment though.
Re: Re: hex to bin
by mt2k (Hermit) on Nov 14, 2002 at 19:30 UTC
    Since you seem to have bin2num, here's bin2dec, taken straight from the pack() docs:

    sub bin2dec { unpack("N", pack("B32", substr("0" x 32 . shift, -32))); }