in reply to How do I 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";

Replies are listed 'Best First'.
Re: Answer: How do I convert between decimal and binary?
by ww (Archbishop) on Jan 20, 2014 at 03:15 UTC

    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
Re: Answer: How do I convert between decimal and binary?
by morgon (Priest) on Jan 20, 2014 at 03:57 UTC
    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.