crc算法java_c语言的crc16算法转java
一、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 校驗(yàn)代碼
*
* @param bufData
* byte類型的數(shù)組數(shù)據(jù)
* @param bufLen
* byte類型的數(shù)組數(shù)據(jù)的長(zhǎng)度
* @return 計(jì)算后的校驗(yàn)碼
*/
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));
}
}
————————————————
版權(quán)聲明:本文為CSDN博主「專注寫bug」的原創(chuàng)文章,遵循 CC 4.0 BY-SA 版權(quán)協(xié)議,轉(zhuǎn)載請(qǐng)附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/qq_38322527/article/details/89881758
總結(jié)
以上是生活随笔為你收集整理的crc算法java_c语言的crc16算法转java的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 《奠基计算机网络》清华大学出版社 之 I
- 下一篇: java里oop思想_(一)OOP思想详