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

How do I convert between decimal and binary?

by vroom (His Eminence)
on Feb 01, 2000 at 23:46 UTC ( [id://2664]=perlquestion: print w/replies, xml ) Need Help??

vroom has asked for the wisdom of the Perl Monks concerning the following question: (numbers)

How do I convert between decimal and binary?

Originally posted as a Categorized Question.

  • Comment on How do I convert between decimal and binary?

Replies are listed 'Best First'.
Re: How do I convert between decimal and binary?
by vroom (His Eminence) on Feb 01, 2000 at 23:48 UTC
    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
      #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?
Re: How do I convert between decimal and binary?
by I0 (Priest) on Jan 03, 2001 at 16:35 UTC
    In v5.6.0 there's $bin = sprintf "%b",$dec; and $dec = oct "0b$bin";
Re: How do I convert between decimal and binary?
by Corion (Patriarch) on May 11, 2003 at 00:09 UTC

    Re: How do I convert between decimal and binary?

    Originally posted as a Categorized Answer.

Re: How do I convert between decimal and binary?
by simmisam (Novice) on Jan 20, 2014 at 02:08 UTC
    chomp (my $inputNumber = <STDIN>); my @array; while ($inputNumber>=1) { my $remainder; my $quo; if ($inputNumber == 1) { unshift @array,$inputNumber; last; } $remainder = $inputNumber % 2; print "Remainder = $remainder\n"; $quo = $inputNumber / 2; print "Quo = $quo\n"; unshift @array,$remainder; $inputNumber = $quo; } print"\n"; print @array; print"\n";

      Either I'm missing something... or there's a little something missing here (like assigning a value to @array):

      C:\>1071258.pl 3 Argument "" isn't numeric in numeric ge (>=) at 1071258.pl line 8, <ST +DIN> line 1.
      where line 8 in my code reflects inclusion of hashbang, etc... and contains while ($inputNumber>=1) and is Ln 4 in OP.

      Update: The node at http://www.perlmonks.com/index.pl?node_id=1071258, the parent of this post, has disappeared (been deleted? by Q&AEditors?) as of approx 0700 Eastern US, 20 Jan 2014, and this reply node contains no link to OP (nor does morgon's similar reply). So, for the record, the OP contained what follows, minus the hashbang, pragmas and source-identifying comment:

      #!/usr/local/bin/perl use 5.016; use warnings; # 1071258 (Q&A: convert between decimal and binary) chomp (my $inputNumber = <STDIN>); my @array; while ($inputNumber>=1) { my $remainder; my $quo; if ($inputNumber == 1) { unshift @array,$inputNumber; last; } $remainder = $inputNumber % 2; print "Remainder = $remainder\n"; $quo = $inputNumber / 2; print "Quo = $quo\n"; unshift @array,$remainder; $inputNumber = $quo; } print"\n"; print @array; print"\n";
      Come, let us reason together: Spirit of the Monastery
      This should not appear as "categorized answers" as it may mislead others.

      Apart from the fact the you don't do any error-handling (e.g. your program does not work for negative numbers, but does not raise an error) the implementation is questionable.

      If your printing of intermediate values is not considered an essential feature you could e.g. simply do this:

      my $binary = sprintf "%b", $inputNumber; my @array = split //, $binary; # if you absolutely want the bits as a +n array
      which may not even be the optimal solution but is clearer, shorter and faster than your attempt.
Re: How do I convert between decimal and binary?
by Anonymous Monk on May 10, 2003 at 02:09 UTC
    143

    Originally posted as a Categorized Answer.

Re: How do I convert between decimal and binary?
by Anonymous Monk on Sep 11, 2003 at 04:42 UTC
    zdzdvfdnyt4rdfsgaerfsh

    Originally posted as a Categorized Answer.

A reply falls below the community's threshold of quality. You may see it by logging in.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (4)
As of 2024-04-25 13:43 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found