Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?

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
Replies are listed 'Best First'.
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]"}
      #!/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);
      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.
Log In?

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

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (7)
As of 2015-11-28 20:17 GMT
Find Nodes?
    Voting Booth?

    What would be the most significant thing to happen if a rope (or wire) tied the Earth and the Moon together?

    Results (744 votes), past polls