C function to Python (different results)
<p>I am trying to port this snippet of code to python from C. The outputs are different even though it's the same code.</p>

<p>This is the C version of the code which works:</p>

<pre><code>int main(void)
{

uint8_t pac[] = {0x033,0x55,0x22,0x65,0x76};
uint8_t len = 5;
uint8_t chan = 0x64;

btLeWhiten(pac, len, chan);

    for(int i = 0;i&lt;=len;i++)
    {
        printf("Whiten %02d \r\n",pac[i]);
     }

   while(1)
   {    

   }

  return 0;
  }



void btLeWhiten(uint8_t* data, uint8_t len, uint8_t whitenCoeff)
{

uint8_t  m;

while(len--){   
    for(m = 1; m; m &lt;&lt;= 1){

        if(whitenCoeff &amp; 0x80){

            whitenCoeff ^= 0x11;
            (*data) ^= m;
        }
        whitenCoeff &lt;&lt;= 1;

    }
    data++;
  }
}
</code></pre>

<p>What I currently have in Python is:</p>

<pre><code>def whiten(data, len, whitenCoeff):
    idx = len 
    while(idx &gt; 0):
        m = 0x01
        for i in range(0,8):
            if(whitenCoeff &amp; 0x80):
                whitenCoeff ^= 0x11
                data[len - idx -1 ] ^= m
                whitenCoeff &lt;&lt;= 1 
                m  &lt;&lt;= 0x01

        idx = idx - 1


pac = [0x33,0x55,0x22,0x65,0x76]
len = 5
chan = 0x64

def main():

whiten(pac,5,chan)
print pac


if __name__=="__main__":
    main()
</code></pre>

<p>The problem i see is that whitenCoeff always remain 8 bits in the C snippet but it gets larger than 8 bits in Python on each loop pass.</p>

<p>You've got a few more problems.</p>

<ol>
<li><code>whitenCoeff &lt;&lt;= 1;</code> is outside of the <code>if</code> block in your C code, but it's inside of the <code>if</code> block in your Python code.</li>
<li><code>data[len - idx -1 ] ^= m</code> wasn't translated correctly, it works backwards from the C code.</li>
</ol>

<p>This code produces the same output as your C code:</p>

<pre><code>def whiten(data, whitenCoeff):
    for index in range(len(data)):
        for i in range(8):
            if (whitenCoeff &amp; 0x80):
                whitenCoeff ^= 0x11
                data[index] ^= (1 &lt;&lt; i)

            whitenCoeff = (whitenCoeff &lt;&lt; 1) &amp; 0xff

    return data

if __name__=="__main__":
    print whiten([0x33,0x55,0x22,0x65,0x76], 0x64)
</code></pre>

python bit-manipulation lfsr