请教关于 c语言 crc16转换成python语言的实现
C语言的算法程序代码:
#include <stdio.h> #include <string> unsigned int Getcrc16(unsigned char *r_data,unsigned int length, unsigned char cInhi, unsigned char cInlo) { unsigned char cl,ch; unsigned char savehi,savelo; int ii,flag; unsigned short CRC; unsigned char crc16hi; unsigned char crc16lo; crc16hi=cInhi;//0xFF; crc16lo=cInlo;//0xFF; cl=0x21; ch=0x10; for (ii=0;ii<length;ii++) { printf("%d=%c ",ii,r_data[ii]); crc16lo=(crc16lo ^ r_data[ii]); for (flag=0;flag<8;flag++) { savehi=crc16hi; savelo=crc16lo; crc16hi=(crc16hi>>1); crc16lo=(crc16lo>>1); if ((savehi & 0x01)==0x01) crc16lo=(crc16lo | 0x80); if ((savelo & 0x01)==0x01) { crc16hi = (crc16hi ^ ch); crc16lo = (crc16lo ^ cl); } } } CRC = (crc16hi)+(crc16lo<<8); // over_turn(2, (unsigned char*)&CRC); return CRC; } len int mylen(char *s) { int i=0; while (s[i]!='\0') { i++; } return i+1; } int main() { const char* s; unsigned int len=0; int i=0; unsigned int rt; unsigned char cInhi=0xFF; unsigned char cInlo=0xFF; unsigned char* sv; char* s2="BDBDBD9000000110010100000900003C000000900000018888888820130117104601000000000000000000000000000000008888888800000000000000000000000000000000000000000000"; printf("aaaaaa\n"); len=mylen(s2); //sv=new unsigned char[len-1] ; for(i=0;i<len-1;i++) { printf("my%d=%c ",i,s2[i]); sv[i]=s2[i]; } printf("\n==============\n"); rt=Getcrc16(sv,len-1,cInhi,cInlo); printf("\n==============\n"); printf("%d\n",&rt); gets(s2); return 0; }
结果是 0BED
我转换的python代码
程序代码:
from struct import pack,unpack def Getcrc16(s,length): print s,length savehi='' savelo='' ii=0 flag=0 CRC='' crc16hi=0xFF; crc16lo=0xFF; cl=0x21; ch=0x10; for ii in range(0,length): crc16lo=(crc16lo ^ int(s[ii] , 16)) for flag in range(0,8): savehi=crc16hi; savelo=crc16lo; crc16hi=(crc16hi>>1); crc16lo=(crc16lo>>1); if ((savehi & 0x01)==0x01): crc16lo=(crc16lo | 0x80); if ((savelo & 0x01)==0x01): crc16hi = (crc16hi ^ ch); crc16lo = (crc16lo ^ cl); CRC = (crc16hi)+(crc16lo<<8); return CRC; def main(): s2='BDBDBD9000000110010100000900003C000000900000018888888820130117104601000000000000000000000000000000008888888800000000000000000000000000000000000000000000' s=Getcrc16(s2,len(s2)) print s,repr(pack('>H',s)) if __name__ == "__main__": main()结果却是\xf7\t
但是结果不同,请问是那里出问题了,有什么好的解决办法