title: Crossover of two binary representations
body: <p>I'm trying to get a quick implementation of the following problem, ideally such that it would work in a numba function. The problem is the following: I have two random integers <code>a</code> &amp; <code>b</code> and consider their binary representation of length <code>L</code>, e.g.</p>
  <p><code>L=4: a=10-&gt;1010</code>, <code>b=6-&gt;0110</code>.</p>
  <p>This is the information that is feed into the function. Then I cut both binary representations in two at the same random position and fuse one of the two results, e.g.</p>
  <p><code>L=4: a=1|010</code>, <code>b=0|110</code> ---&gt; c=<code>1110</code> or <code>0010</code>.</p>
  <p>One of the two outcome is chosen with equal probability and that is the outcome of the function. The cut occurs between the first 1/0 and the last 0/1 of the binary representation.</p>
  <p>This is currently my code:</p>
  <pre><code>def func(a,b,l):
      bin_a = [int(i) for i in str(bin(a))[2:].zfill(l)]
      bin_b = [int(i) for i in str(bin(b))[2:].zfill(l)]
      randint = random.randint(1, l - 1)
      print(&quot;randint&quot;, randint)
      if random.random() &lt; 0.5:
          result = bin_a[0:randint]+bin_b[randint:l]
      else:
          result = bin_b[0:randint] + bin_a[randint:l]
      return result
  </code></pre>
  <p>I have the feeling that there a possibly many shortcuts to this problem that I do not come up with. Also my code does not work in numba :/. Thanks for any help!</p>
  <p><strong>Edit</strong>: This is an update of my code, thanks to Prunes help! It also works as a numba function. If there is no further improvements to that, I would close the question.</p>
  <pre><code>def func2(a,b,l):
      randint = random.randint(1, l - 1)
      print(&quot;randint&quot;, randint)
  
      bitlist_l = [1]*randint+[0]*(l-randint)
      bitlist_r = [0]*randint+[1]*(l-randint)
      print(&quot;bitlist_l&quot;, bitlist_l)
      print(&quot;bitlist_r&quot;, bitlist_r)
      l_mask = 0
      r_mask = 0
      for i in range(l):
          l_mask = (l_mask &lt;&lt; 1) | bitlist_l[i]
          r_mask = (r_mask &lt;&lt; 1) | bitlist_r[i]
      print(&quot;l_mask&quot;, l_mask)
      print(&quot;r_mask&quot;, r_mask)
      if random.random() &lt; 0.5:
          c = (a &amp; l_mask) | (b &amp; r_mask)
      else:
          c = (b &amp; l_mask) | (a &amp; r_mask)
      return c
  </code></pre>