title: How to merge two binary numbers into a ternary number
body: <p>I have two binary integers, <code>x0</code> and <code>x1</code> that are 8 bits (so they span from 0 to 255).  This statement is always true about these numbers: <code>x0 &amp; x1 == 0</code>.  Here is an example:</p>
  
  <pre><code>bx0 = 100 # represented as 01100100 in binary
  bx1 = 129 # represented as 10000001 in binary
  </code></pre>
  
  <p>So I need to do the following operation on these numbers.  First, interpret these binary representations as <a href="https://en.wikipedia.org/wiki/Ternary_numeral_system" rel="nofollow noreferrer">ternary</a> (base-3) numbers, as follows:</p>
  
  <pre><code>tx0 = ternary(bx0) # becomes  981 represented as 01100100 in ternary
  tx1 = ternary(bx1) # becomes 2188 represented as 10000001 in ternary
  </code></pre>
  
  <p>Then, swap all of the <code>1</code> in the ternary representation of <code>tx1</code> to <code>2</code>:</p>
  
  <pre><code>tx1_swap = swap(tx1) # becomes 4376, represented as 20000002 in ternary
  </code></pre>
  
  <p>Then use a ternary version of <code>OR</code> on them to get the final combined number:</p>
  
  <pre><code>result = ternary_or(tx0, tx1_swap) # becomes 5357, represented as 21100102 in ternary
  </code></pre>
  
  <p>I don't need the ternary representation saved at any point, I only need the result, where for example <code>result=5357</code>.  Of course I could code this by converting the numbers to binary, converting to ternary, etc.. but I need this operation to be fast because I am doing this many times in my code.  What would a fast way to implement this in python? </p>