title: Conversion of binary bitstream to and from ternary bitstream?
body: <p>I need to convert arbitary length binary into an exact ternary representation. Ideally, given an array of bits <code>char buffer[n]</code>, the algorithm would be able to produce a array of trits(analog of bits), and vice versa. Is there such an algorithm?</p>
  
  <p>I am aware of ways to convert individual <code>int</code> to ternary:</p>
  
  <pre><code>int nth_trit(int num, int n)
  {
      for(int i = 0; i &lt; n; i++)
          num /= 3;
  
      return num % 3;
  }
  </code></pre>
  
  <p>Alas, with a bitstream even a <code>long long long int</code> wouldn't suffice. I think using a big integer library would suffice, although I'm not sure, and feel that there should be better way calculate the ternary representation.</p>
  
  <p>A visual example:</p>
  
  <pre><code>// Conversion is simple(short stream)
  Binary  - 0 1 0 0 1 0 0 1
  Decimal -             7 3
  Ternary -         2 2 0 1
  
  // Conversion is hard(long stream)
  Binary  - 1 0 1 0 0 0 0 1 ..........
  Ternary - ? ? ?
  </code></pre>
  
  <p>The short stream is simple because, since it nicely fits into an <code>int</code>, the <code>nth_trit</code> function can be used, but the long stream doesn't, and so apart from using a big integer library, no easy solution occurs to me.</p>