关于CRC16校验的

youyiyang 2016-11-18 10:35:16
各位好!我在android蓝牙4.0开发的时候碰到CRC16校验码生成的问题,我根据资料上写的CRC校验子程序算出来的老是不对,请哪位大侠看看是哪里搞错了?是不是我在byte和int以及string上搞混淆了?
代码如下:

public byte[] getCRC(byte[] input, int input_length){
int reg_crc=0xFFFF;
//input_length--;
for (int i=1;i<input_length;i++){
Toast.makeText(Commviewer_ControlActivity.this, i+", "+String.valueOf((int)input[i]), Toast.LENGTH_SHORT).show();
reg_crc ^= input[i];
for (int j=0;j<8;j++){
//reg_crc=reg_crc>>1;
if((reg_crc & 0x01)==1){
reg_crc=(reg_crc>>1)^0xA001;
}else{
reg_crc=reg_crc>>1;
}
}
}
byte[] crcByte = new byte[2];
crcByte[0] = (byte)((reg_crc >> 8) & 0xFF);
crcByte[1] = (byte) (reg_crc & 0xFF);
// 将新生成的byte数组添加到原数据结尾并返回
return concatAll(input, crcByte);
}

public byte[] concatAll(byte[] input_array, byte[] crcB){
byte[] result = new byte[input_array.length + 3];
System.arraycopy(input_array,0,result,0,input_array.length);
result[input_array.length]=crcB[1];
result[input_array.length+1]=crcB[0];
result[input_array.length+2]=0x18;
return result;
}

有这么一串数据:

byte[] WriteBytes = new byte[17];
WriteBytes[0]=0x66;
WriteBytes[1]=0x00;
WriteBytes[2]=0x0B;
WriteBytes[3]=0x00;
WriteBytes[4]=0x10;
WriteBytes[5]=0x00;
WriteBytes[6]=0x10;
WriteBytes[7]=0x11;
WriteBytes[8]=0x22;
WriteBytes[9]=0x33;
WriteBytes[10]=0x44;
WriteBytes[11]=0x55;
WriteBytes[12]=0x66;
WriteBytes[13]=0x77;
WriteBytes[14]=(byte)0x88;
WriteBytes[15]=(byte)0x99;
WriteBytes[16]=(byte)0xFF;

就是:
66 00 0B 00 10 00 10 11 22 33 44 55 66 77 88 99 FF
我写的程序就是从第2位到第17位进行CRC计算。
00 0B 00 10 00 10 11 22 33 44 55 66 77 88 99 FF
用我写的代码算出是 03 DF(低字节在前,高字节在后)
用网上下载的crc16软件算出的是BD D0(低字节在前,高字节在后)
到底是哪里出错了?
...全文
58 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
qq_30018879 2017-11-07
  • 打赏
  • 举报
回复
楼主,在不,为什么调用的时候结果会多出三位数呀??
youyiyang 2016-11-18
  • 打赏
  • 举报
回复
哦,是我子程序写错了应该这么写:

public byte[] getCRC(byte[] input, int input_length){
	    int reg_crc=0xFFFF;
    	//input_length--;
    	for (int i=1;i<input_length;i++){
	    	//Toast.makeText(Commviewer_ControlActivity.this, i+", "+String.valueOf((int)input[i]), Toast.LENGTH_SHORT).show();
    		reg_crc ^= (int)(input[i]&0xFF);
    		for (int j=0;j<8;j++){
    			if((int)(reg_crc & 0x01)==1){
    				reg_crc=(reg_crc>>1)^0xA001;
    		    }else{
    		    	reg_crc=reg_crc>>1;
    		    }
    		}
    	}
一光年lost 2016-11-18
  • 打赏
  • 举报
回复
这个对所有的字节数组都适用吗?

80,349

社区成员

发帖
与我相关
我的任务
社区描述
移动平台 Android
androidandroid-studioandroidx 技术论坛(原bbs)
社区管理员
  • Android
  • yechaoa
  • 失落夏天
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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