in reply to Base10 to Base2.

Hello monk, first I recommend you to search before posting.
You can see the same question clicking here.
My way to do this is the following:
#!/usr/bin/perl print "Enter number (DECIMAL): ";chomp($dec=<STDIN>); while($dec){ $dec = int($dec); @base = reverse(split(/\^*/,$dec)); $intB = int($base[0]/2); $noIntB = $base[0]/2; if($intB eq $noIntB){$temp="0"} else{$temp="1"}push(@binary,$temp); $dec /= 2; if($dec < 1){last} } print "Binary : " . reverse(@binary),"\n";

Replies are listed 'Best First'.
Re: Re: Base10 to Base2.
by strider corinth (Friar) on Oct 21, 2002 at 18:45 UTC
    Another implementation of (essentially) this same algorithm:
    print "Enter a decimal number: "; chomp( $decimal = <STDIN> ); $binary = ''; while( $decimal ){ $binary = $decimal%2 . $binary; $decimal = int( $decimal/2 ); } print STDOUT $binary;
    I think tadman's answer in the previous thread was more elegant (but apparently it only works in 5.6 or higher):
    my ($binary) = sprintf ("%08b", $decimal);
    --

    Love justice; desire mercy.