Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Answer: How do I convert between decimal and binary?

( #2665=categorized answer: print w/ replies, xml ) Need Help??

Q&A > numbers > How do I convert between decimal and binary? contributed by vroom

We need to use pack and unpack because printf or sprintf don't have any way of dealing with binary numbers. Here are two functions that should do the job though:
sub dec2bin { my $str = unpack("B32", pack("N", shift)); $str =~ s/^0+(?=\d)//; # otherwise you'll get leading zeros return $str; } sub bin2dec { return unpack("N", pack("B32", substr("0" x 32 . shift, -32))); }
To turn a perl integer into a binary string we must first pack it into network byte order which the "N" format stands for. Then we unpack it into the "B32" format. We then strip off all leading 0's with a simple substitution.

For the bin2dec function we simply reverse the process. First we pad the number with the correct number of 0's and then reversing what we did in the previous function

Comment on Answer: How do I convert between decimal and binary?
Download Code
Re: Answer: How do I convert between decimal and binary?
by I0 (Priest) on Dec 19, 2000 at 17:06 UTC
    #or, in v5.6.0 sub dec2bin {return sprintf "%b",shift } #and sub bin2dec{ return oct"0b$_[0]"}
      I have 32 bits, that I need to convert to decimal. This seems to be a problem for bin2doc. Do I encounter an overflow?
        Shouldn't be a problem; what version of perl are you using? 0b is only supported as of 5.6.0.
      #!/user/local/bin/perl print "\nEnter the num:"; @rem=(); $dec =<STDIN>; print "converting to binary"; while ($dec> 0) { @rem$i++ = $dec % 2; $dec= int ($dec/2); } print reverse(@rem);
Log In?
Username:
Password:

What's my password?
Create A New User
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (13)
As of 2014-09-22 20:18 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (200 votes), past polls