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><code>whitenCoeff &lt;&lt;= 1</code> in C becomes 0 after a while because it is a 8-bit data.</p>

<p>In python, there's no such limit, so you have to write:</p>

<pre><code>whitenCoeff = (whitenCoeff&lt;&lt;1) &amp; 0xFF
</code></pre>

<p>to mask higher bits out.</p>

<p>(don't forget to check vz0 remark on array boundary)</p>

<p>plus there was an indentation issue.</p>

<p>rewritten code which gives same result:</p>

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

        idx = idx - 1


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

def main():

    whiten(pac,chan)
    print(pac)


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

<p>Slightly off-topic: Note that the C version already has problems:</p>

<pre><code>for(int i = 0;i&lt;=len;i++)
</code></pre>

<p>should be</p>

<pre><code>for(int i = 0;i&lt;len;i++)
</code></pre>

python bit-manipulation lfsr