in reply to Why does it return 0?

sub dec2bin { my $inNumber = shift; my $sign = $inNumber=~s/^-// ? '-' : ''; return $sign.sprintf "%b", $inNumber; }
is how I'd do it (untested). (The "%b" format was added in perl 5.6.0.) Don't forget to actually use the parameter you pass. Also, in your code $binnumb = $binnumb . $binary would be usually written $binnumb .= $binary. (Either is exempt from the usual warning that $binnumb is undefined; other operators special-cased this way are +, -, ||, &&, ^, |, ++, --.)

Replies are listed 'Best First'.
Re: Re: Why does it return 0?
by mAineAc (Novice) on Feb 05, 2004 at 02:17 UTC
    I tried to use the $binnumb .= $binary but it doesn't seem to be concatenating the string it just returns the last value of $binary.
      In your original code, you needed to have had a loop, doing the % and / and append until the number is zero. But you're better off just using sprintf "%b" or unpack.

      Update: except that you'd have to do $binnumb = $binary . $binnumb instead, which will get a warning unless you initialize $binnumb to '' at the start. And you need to handle negative numbers.

        Yea I realize I have to handle negative numbers still. I did get it to work with a while loop like this:
        sub dec2bin { my $binnumb; while($inNumber > 0) { my $binary = $inNumber % 2; print $inNumber; print "\n"; $inNumber = int($inNumber / 2); $binnumb .= $binary; print $binnumb; print "\n"; } $binnumb = reverse $binnumb; return $binnumb; }
        I wasn't thinking when I tried to do it with an if statement. I don't get any errors with this and it gives me the right number. I just didn't understand the code that you gave me at first. What does %b do?