in reply to Base10 to Base2.

The question is: do you know how to do it "by hand"? Here's my process (the number that you want to convert is n):
  1. Find the largest k such that 2k ≤ n. Your binary number k+1 digits, starting with a 1
  2. Subtract 2k from your n.
  3. Subtract 1 from k.
  4. If 2k is larger than n, put a 0 down in your binary number. If k is smaller or equal to n, place a 1 in your binary number, and subtract 2k from n.
  5. redo the previous step until k is 0.
Now, here's a simple example for n=10:
  1. 20 = 1 ≤ 10,
    21 = 2 ≤ 10,
    22 = 4 ≤ 10,
    23 = 8 ≤ 10,
    24 = 16 > 10.
    Thus, k=3, and our binary digit will have 4 bits, starting with a 1.
  2. n=10-23=2,
    k=3-1=2
  3. 22 = 4 > 2, so we put a 0.
    k=2-1=1
  4. 21 = 2 ≤ 2, so we put a 1.
    k=1-1=0,
    n=2-21=0
  5. 20 = 1 > 0, so we put a 0.
  6. So, our net result is 1010
From this, you should be able to code your algorithm. A for loop comes to mind...;)

thor

Replies are listed 'Best First'.
Re: Re: Base10 to Base2.
by fruiture (Curate) on Oct 21, 2002 at 19:09 UTC

    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
      To paraphrase my college analysis professor: I was going to leave that as an exercise to the reader. ;)

      thor