📄 crcsum.c
字号:
// ABB电表密码处理程序,ALPHA协议
unsigned long EncryptionKey(unsigned char *radomkey, unsigned long pword)
{
int i; /*loop index */
int j,k=0; /*used to simulate rotate */
union {
unsigned long key; /*encryptin key */
struct{
unsigned char byta,bytb,bytc,bytd;
} parts;
}val;
val.parts.byta = radomkey[3];
val.parts.bytb = radomkey[2];
val.parts.bytc = radomkey[1];
val.parts.bytd = radomkey[0];
/* Add an arbitrary number to the key just for fun. */
val.key += 0xab41;
/* Generate a four bit checksum to be used as loop index . */
i = val.parts.byta + val.parts.bytb + val.parts.bytc + val.parts.bytd;
i = i & 0x0f;
while ( i>=0) {
/* Set 'j' to the value of the high bit before shifting. Simulates carry flag. */
if(val.parts.bytd >=0x80)
j = 1;
else
j = 0;
/* Shift the key. Add in the carry flag from the previous loop. */
val.key = val.key << 1;
val.key += k;
k = j;
/* Apply the key to the password. */
pword ^= val.key;
i--;
} // end of while
return pword;
}
// 本检验和支持以下电表通讯协议
// IEC1107协议
// DLT645
unsigned char Iec1107CheckSum(unsigned char *buf, unsigned char len)
{
unsigned char i,c=0;
for(i=1;i<len;i++)
c ^=buf[i];
return c;
}
// 该校验码计算程序支持以下规约
// ModBus规约
// ION规约
// EDMI规约
unsigned int GetCrc16(char *buf, unsigned int len)
{
int i,flag;
unsigned int crc = 0;
while( len--)
{
crc ^= ((unsigned int)(*buf++))<<8;
for(i=0;i<8;i++)
{
flag = crc & 0x8000;
crc <<=1;
if( flag )
crc ^= 0x1021;
}
}
return (crc);
}
//CRC校验计算函数
//ION表的ModBus规约
unsigned int GetMbusCrc16(unsigned char *ptr, unsigned int len)
{
unsigned int crc=0xffff;
unsigned char i;
while(len!=0)
{
crc^=*ptr;
for(i=0;i<8;i++)
{
if((crc&0x0001)==0)
crc=crc>>1;
else
{
crc=crc>>1;
crc^=0xa001;
}
}
len-=1;
ptr++;
}
return crc;
}
// 支持以下电表规约
// QUAD4 规约
unsigned int Quad4CRC(unsigned char *buf, unsigned int len)
{
unsigned int iCRC;
unsigned char cData;
unsigned char i,k;
unsigned int CRC;
unsigned int XorConst = 0x8005;
CRC = 0;
for(k=0;k<len;k++){
cData=buf[k];
for (i = 0; i < 8; i++){
if ((cData & 0x80) != ((CRC >> 8) & 0x80)){
CRC <<= 1;
CRC ^= XorConst;
cData <<= 1;
}
else{
CRC <<= 1;
cData <<= 1;
}
}
}
return (CRC);
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -