in reply to Re: Re: Re: Why does it return 0?
in thread Why does it return 0?

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?

Replies are listed 'Best First'.
Re: Re: Re: Re: Re: Why does it return 0?
by ysth (Canon) on Feb 05, 2004 at 03:24 UTC
    %b formats a number as binary (but first casts it to an unsigned value, so you'd need to make sure you only feed it positive values):
    $ perl -we'printf "%b", 123' 1111011
    (printf outputs directly, sprintf returns a formatted string).

    Looks like your code above will give undef for 0; I think that could be fixed by changing your while () {} do a do {} while ().