[Tutor] help with translating a c function to a python function
keridee at jayco.net
Sun Jul 8 21:44:13 CEST 2007
>> i have a c function from some modbus documentation that i need to
>> translate into python.
>> unsigned short CRC16(puchMsg, usDataLen)
>> unsigned char *puchMsg ;
>> unsigned short usDataLen ;
>> unsigned char uchCRCHi = 0xFF ;
>> unsigned char uchCRCLo = 0xFF ;
>> unsigned uIndex ;
>> while (usDataLen––)
>> uIndex = uchCRCHi ^ *puchMsgg++ ;
>> uchCRCHi = uchCRCLo ^ auchCRCHi[uIndex} ;
>> uchCRCLo = auchCRCLo[uIndex] ;
>> return (uchCRCHi << 8 | uchCRCLo) ;
I found this link which may provide some insight into what's going on here.
(google "modbus CRC16")
This proves to me that auchCRCHi is a lookup table that you do not have
access to. Happily :-) that link provides the table.
Hmmm... let's see, the difficult C stuff... *puchMsgg++ means to return the
current character in a string, and then increment the pointer, so that when
the C code encounters *puchMsgg++ again it reads the next character,
increments, etc. You can emulate this with an index and array notation in
^ , << , and | are all bitwise operators, and python uses all of these
in the same way as C
'^' means XOR exclusive OR.
0101 ^ 0011 = 0110 i.e. 5 ^ 3 = 6
'<< ' means left - shift
0010 << 2 = 1000 i.e. a << b = a * (2**b)
'|' means OR.
0101 ^ 0011 = 0111 i.e. 5 ^ 3 = 7
puchMsgg is basically a string
and all the unsigned stuff are (very roughly) integers.
More information about the Tutor