Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C function to Python (different results)

I am trying to port this snippet of code to python from C. The outputs are different even though it's the same code.

This is the C version of the code which works:

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<=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 <<= 1){

        if(whitenCoeff & 0x80){

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

    }
    data++;
  }
}

What I currently have in Python is:

def whiten(data, len, whitenCoeff):
    idx = len 
    while(idx > 0):
        m = 0x01
        for i in range(0,8):
            if(whitenCoeff & 0x80):
                whitenCoeff ^= 0x11
                data[len - idx -1 ] ^= m
                whitenCoeff <<= 1 
                m  <<= 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()

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.

like image 914
Dimo Avatar asked Sep 04 '26 08:09

Dimo


1 Answers

You've got a few more problems.

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

This code produces the same output as your C code:

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

            whitenCoeff = (whitenCoeff << 1) & 0xff

    return data

if __name__=="__main__":
    print whiten([0x33,0x55,0x22,0x65,0x76], 0x64)
like image 61
Blender Avatar answered Sep 06 '26 23:09

Blender