Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

hex to bin

by Eureka_sg (Monk)
on Mar 09, 2001 at 07:07 UTC ( [id://63158]=perlquestion: print w/replies, xml ) Need Help??

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

how do we convert a hex to a bin and vice versa?

Replies are listed 'Best First'.
Re: hex to bin
by I0 (Priest) on Mar 09, 2001 at 09:09 UTC
    $bin = sprintf "%b", oct "0x$hex"; $hex = sprintf "%x", oct "0b$bin";
Re: hex to bin
by Adam (Vicar) on Mar 09, 2001 at 07:22 UTC
    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 )
      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.
      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))); }
Re: hex to bin
by OzzyOsbourne (Chaplain) on Mar 09, 2001 at 21:33 UTC
    What about pack ("L",$foo) or pack ("h", $foo)?

    -OzzyOsbourne

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others sharing their wisdom with the Monastery: (6)
As of 2024-04-23 19:19 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found