Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery

Answer: How do I convert between decimal and binary?

by vroom (Pope)
on Feb 01, 2000 at 23:48 UTC ( #2665=categorized answer: print w/replies, xml ) Need Help??

Q&A > numbers > How do I convert between decimal and binary? - Answer 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

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 all is quiet...

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (2)
As of 2018-05-26 16:15 GMT
Find Nodes?
    Voting Booth?