Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Re: hex to bin

by Adam (Vicar)
on Mar 09, 2001 at 07:22 UTC ( [id://63160]=note: print w/replies, xml ) Need Help??


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))); }

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://63160]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others examining the Monastery: (3)
As of 2024-04-19 17:35 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found