crc算法java_c语言的crc16算法转java

该博客分享了C语言和Java语言实现CRC校验的代码。C语言版本的`uint16_tcrc_chk`函数和Java的`crc_chk`方法都用于计算字节数据的CRC校验码。在Java实现中,还提供了`HexString2Bytes`方法将十六进制字符串转换为字节数组。这些函数可用于数据传输的正确性验证。
摘要由CSDN通过智能技术生成

一、c语言

uint16_t crc_chk(uint8_t *data, uint8_t len)

{

uint8_t i;

uint16_t reg_crc = 0xffff;

while(len--) {

reg_crc ^= *data++;

for(i = 0; i < 8; i++) {

if(reg_crc & 0x01) {

reg_crc = (reg_crc >> 1) ^ 0xA001;

} else {

reg_crc = reg_crc >> 1;

}

}

}

return reg_crc;

}

二、java语言

public class TestDemo {

/**

* crc 校验代码

*

* @param bufData

* byte类型的数组数据

* @param bufLen

* byte类型的数组数据的长度

* @return 计算后的校验码

*/

public static String crc_chk(byte[] bufData, int bufLen) {

int reg_crc = 0xffff;

for (int i = 0; i < bufLen; i++) {

reg_crc ^= ((int) bufData[i] & 0xff);

for (int j = 0; j < 8; j++) {

if ((reg_crc & 0x01) != 0) {

reg_crc = (reg_crc >> 1) ^ 0xa001;

} else {

reg_crc = reg_crc >> 1;

}

}

}

return Integer.toHexString(reg_crc);

}

public static byte[] HexString2Bytes(String src) {

byte[] ret = new byte[src.length() / 2];

byte[] tmp = src.getBytes();

for (int i = 0; i < tmp.length / 2; i++) {

ret[i] = uniteBytes(tmp[i * 2], tmp[i * 2 + 1]);

}

return ret;

}

public static byte uniteBytes(byte src0, byte src1) {

byte _b0 = Byte.decode("0x" + new String(new byte[] { src0 })).byteValue();

_b0 = (byte) (_b0 << 4);

byte _b1 = Byte.decode("0x" + new String(new byte[] { src1 })).byteValue();

byte ret = (byte) (_b0 ^ _b1);

return ret;

}

public static void main(String[] args) {

String ss = "AB0B0701140267010501";

byte[] dd = HexString2Bytes(ss);

System.out.println(crc_chk(dd, dd.length));

}

}

————————————————

版权声明:本文为CSDN博主「专注写bug」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。

原文链接:https://blog.csdn.net/qq_38322527/article/details/89881758

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值