M
modaji
Unregistered / Unconfirmed
GUEST, unregistred user!
CRC运算<br><br>uchar bus_recv_buf[] ; 接收缓存区位置<br>长度=第1字节去掉高4位,CRC的字节高4位强制为3<br>函数返回1 CRC正确<br>返回0 CRC错误<br>uchar chk_crc16(void)<br>{<br> uchar l, n;<br> uint crc;<br> uchar ch, cl;<br> uchar i;<br> crc = 0x0000;<br> l = (bus_recv_buf[0]&0x0f) - 2; //长度=第1字节去掉高4位<br> for (n = 0; n < l; n++)<br> {<br> crc = crc ^ ((uint)bus_recv_buf[n] << 8);<br> for (i = 0; i < 8; ++i)<br> if (crc &0x8000)<br> crc = (crc << 1) ^ 0x1021;<br> else<br> crc = crc << 1;<br> }<br> crc &= 0x0f0f;<br> crc |= 0x3030; // CRC的字节高4位强制为3<br> l = (bus_recv_buf[0] &0x0f); //长度为第1字节去掉高4位<br> ch = bus_recv_buf[l - 2]; <br> cl = bus_recv_buf[l - 1]; <br> if (crc == (((uint)ch) << 8) + cl)<br> {<br> return (1);<br> }<br> else<br> {<br> return (0);<br> }<br>}<br><br>我把它改成Delphi,如下:<br><br>type<br> TBytes=array of Byte <br>var<br> ReBuffer:TByte;//接受缓冲区<br> <br><br><br><br>//此函数是网上看到的,顺便拿来用,不知有错误么?---Byte数组转换为integer-------------------<br>function BytesToInteger(const AValue: TBytes): Integer; <br>begin <br> {$IFDEF DotNet} <br> Result := System.BitConverter.ToInt32(AValue, 0); <br> {$ELSE} <br> Result := PInteger(@AValue[0])^; <br> {$ENDIF} <br>end;<br>//----------------------------------------------------------<br><br>{-------------------------------------------------------<br>长度=第1字节去掉高4位,CRC的字节高4位强制为3<br>函数返回true CRC正确<br>返回false CRC错误<br>--------------------------------------------------------}<br>function Check_RCR():Boolean;<br>var<br> L,n: byte;<br> crc:integer;<br> ch,cl,i:byte;<br>begin<br> result:=false;<br> crc:=$0000;<br> L:=(ReBuffer[0] and $0f)-2; //长度=第1字节去掉高4位<br> for n:=0 to L do<br> begin<br> crc:=crc xor (BytesToInteger(ReBuffer[n]) shl 8);//调用转换函数,这一句有问题,提示说,Byte和Bytes类型不匹配,请问,怎么改?<br> //crc:=crc xor (ReBuffer[n] shl 8);<br> for i:=0 to 7 do<br> begin<br> if (crc and $8000) then<br> crc:=((crc shl 1) xor $1021)<br> else<br> crc:=crc shl 1;<br> end;//end for i:=0 to 7 do<br> end;//end for n:=0 to 1 do<br> crc:= crc and $0f0f;<br> crc:= crc or $3030;<br> L:=(ReBuffer[0] and $0f);<br> ch:=ReBuffer[L-2];<br> cl:=ReBuffer[L-1];<br> //if (crc=(ch shl 8) + cl) then//ch类型转换:byte型怎么转换为integer型?<br> if crc= (ch *256 +cl) then//这一句不知可不可以?<br> result:=true<br> else<br> result:=false;<br><br>end;<br><br>问题在注释上,我是新手,很多东西不懂,请大家帮我看看吧,如果能够顺便帮我修改修改,小弟将感激不尽!