110,533
社区成员
发帖
与我相关
我的任务
分享
#include <string.h>
unsigned int cal_crc(unsigned char *ptr, unsigned char len)
{
unsigned char i;
unsigned int crc=0;
while(len--!=0)
{
for(i=0x80; i!=0; i/=2)
{
if((crc&0x8000)!=0)
{
crc*=2;
crc^=0x1021;
} /* 涌CRC 乘?郧CRC */
else
crc*=2;
if((*ptr&i)!=0) crc^=0x1021; /* 约涌究的RC */
}
ptr++;
}
return crc;
}
int main(int argc,char* argv[])
{
char* strBytes = NULL;
unsigned char strTemp[3] = {0};
int len = 0,i,j,byteLen = 0;
unsigned int crc_ret = 0;
unsigned char byteArray[56] = {0};
if(argc < 2)
return -1;
strBytes = argv[1];
len = strlen(strBytes);
for(i = 0,byteLen; i < len;i+=2)
{
memcpy(strTemp,strBytes+i,2);
byteArray[byteLen++] = strtoul(strTemp,NULL,16);
}
printf("ByteArray[%d]:",byteLen);
for(j = 0;j < byteLen;j++)
{
printf("%02X ",byteArray[j]);
}
crc_ret = cal_crc(byteArray, byteLen);
printf("\nCRC:%02X %02X\n",(crc_ret>>8 & 0xff),(crc_ret & 0xff));
return 0;
}
static/*这个是静态类 需要 static*/ uint cal_crc(byte[] ptr, byte len/*这里没有意义 byte[] 有 Length属性*/) {
byte i;
uint crc = 0;
for (int j = 0; j < ptr.Length; j++) {
for (i = 0x80; i != 0; i /= 2) {
if ((crc & 0x8000) != 0) {
crc *= 2;
crc ^= 0x1021;
} /* 涌CRC 乘?郧CRC */
else
crc *= 2;
if ((ptr[j] & i) != 0) crc ^= 0x1021; /* 约涌究的RC */
}
}
return crc;
}
[STAThread]
static int Main(string[] args) {
string strBytes = null;
byte[] strTemp = new byte[3];
int len = 0, i, j, byteLen = 0;
uint crc_ret = 0;
byte[] byteArray = new byte[56];
if (args.Length < 2)
return -1;
strBytes = args[1];
len = strBytes.Length;
for (i = 0, byteLen = 0; i < len; i += 2) {
//memcpy(strTemp, strBytes + i, 2);
byteArray[byteLen++] = Convert.ToByte(strBytes.Substring(i, 2), 16);// strtoul(strTemp, NULL, 16);
}
Console.Write("ByteArray:" + byteLen);
for (j = 0; j < byteLen; j++) {
Console.Write(byteArray[j].ToString("X").PadLeft(2, '0'));
}
crc_ret = cal_crc(byteArray, (byte)byteLen);
Console.Write(string.Format("\nCRC:{0} {1}\n", (crc_ret >> 8 & 0xff).ToString("X").PadLeft(2, '0'), (crc_ret & 0xff).ToString("X").PadLeft(2, '0')));
return 0;
}
这个是按照字面上的代码 直接翻译过来的 没有测试执行结果
不过 翻译成 C# 代码 有很多代码 已经没有必要了 很多可以优化的地方 比如上面说的 byte[] 他已经自带length属性了 没有必要需要 len 参数了 main 里面也有很多 可以很方便的写法
自己搞吧