请教CRC校验算法

haogaoxiao 2010-09-15 11:49:02
有这样一个字符条码 VIPY 1D 000007 其中1D是VIPY000007的校验码,请大侠们帮看看CRC算法改怎么写,下面有厂商提供的算法,能否帮改写成C#的


unsigned char RedGetFc(char *pack,unsigned int len)
{
#define CRCNUM 0xa001
unsigned char test,crclow,crchigh,recode;
unsigned int i,j,crcnum=0xffff,t;
if(len==0)
return(-1);
for(i=1;i<=len;i++)
{
test=*pack;
crclow=(char)crcnum;
crchigh=(char)(crcnum>>8);
crcnum=(unsighed int)(test^crclow)+((unsighed int)crchigh)*256;
for(j=1;j<=8;j++)
{
t=crcnum&0x0001;
crcnum=crcnum>>1;
if(t)
{
crcnum=crcnum^CRCNUM;
}
}
pack++;
}
recode=(unsighed char)crcnum;
return(recode);
}
...全文
102 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
兔子-顾问 2010-09-16
  • 打赏
  • 举报
回复
string checksum = RedGetFc("VIPY000007",(uint)"VIPY000007".Length).ToString("X2");
结果是1B
兔子-顾问 2010-09-15
  • 打赏
  • 举报
回复
byte RedGetFc(string pack, uint len)
{
const ushort CRCNUM = 0xa001;
byte test, crclow, crchigh, recode;
uint j, crcnum = 0xffff, t;
if (len == 0) return 0xFF;
for (int i = 1; i <= len; i++)
{
test = (byte)pack[i - 1];
crclow = (byte)crcnum;
crchigh = (byte)(crcnum >> 8);
crcnum = (uint)(test ^ crclow) + ((uint)crchigh) * 256;
for (j = 1; j <= 8; j++)
{
t = crcnum & 0x0001;
crcnum = crcnum >> 1;
if (t != 0)
{
crcnum = crcnum ^ CRCNUM;
}
}
}
recode = (byte)crcnum;
return (recode);
}
haogaoxiao 2010-09-15
  • 打赏
  • 举报
回复
多谢wuyazhe,1楼的算法和我另外找的算法得到一样的结果
用VIPY000007来计算,得到的 crcnum 都是 56859

然后这样转换

byte[] rebuf = BitConverter.GetBytes(crcnum);
string Re = Convert.ToBase64String(rebuf);


rebuf[0]=27,rebuf[1]=222
1楼的算法得到的是27
转换的Re="G94="
算法估计没有错,但是不知道怎么转换得到校验码1D
Encoding.Default.GetBytes("1D")得到buf[0]=49,buf[1]=68

110,538

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧