in reply to Re: Base10 to Base2.
in thread Base10 to Base2.

More general: how to convert number n to base b.

  1. bk ≤ n; find k; k = floor( logbn )
  2. t * bk ≤ n; find t; t = floor( n/bk )
  3. put sign nr. t from your base at end of resulting string, there must be exactly b signs in the base array.
  4. set n = n - t * bk
  5. go to step 1 or finish if n = 0

in other words:

sub decimalToX { my $number = shift or return $_[0]; my $base = @_; my $logbase = log $base; my $string = ''; my $power = int(log($number)/$logbase); while($number){ my $f = $base ** $power; my $times = int($number/$f); $string .= $_[$times]; $number -= $times * $f; } continue { --$power } $string . $_[0] x ($power+1) } print decimaltoX( 5 , qw/0 1/ ); # 101
--
http://fruiture.de

Replies are listed 'Best First'.
Re: Re: Re: Base10 to Base2.
by thor (Priest) on Oct 22, 2002 at 13:14 UTC
    To paraphrase my college analysis professor: I was going to leave that as an exercise to the reader. ;)

    thor