java crc16 1021_标准crc16,通用javascript,java,c语言

java实现

/**

*

* 标准CRC16校验码

*

* @decimalBytes 输入十进制的字节数组

* @return 返回uint16的数字

*

* demo const {decimalBytes} = GMTools.transToUTF8('123456789'); let

* crc = GMTools.crc16(decimalBytes); hexCRC =

* GMTools.uint16ToHexString(crc); console.log(hexCRC); // 29b1

*

*/

public static int crc16(char[] decimalBytes) {

int crc = 0xFFFF;

String[] tabccitt = new String[256];

int indx = 0;

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

int ccitt = 0;

int c = i << 8;

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

if (((ccitt ^ c) & 0x8000) > 0) {

ccitt = (ccitt << 1) ^ 0x1021;

} else {

ccitt = ccitt << 1;

}

c = c << 1;

}

tabccitt[indx++] = uint16ToHexString(ccitt);

}

for (char c : decimalBytes) {

int sc = 0x00FF & c;

int index = (0xFFFF) & ((crc >>> 8) ^ sc);

int n = Integer.parseInt(tabccitt[index], 16);

crc = (0xFFFF) & ((0xFFFF) & (crc << 8)) ^ ((0xFFFF) & n);

}

return crc;

}

c 语言实现,stm32都可以用

/**

* 标准的CRC校验算法

* @src 校验字符串首地址

* @sizes 总字节数

*/

unsigned short crc16(const char *src, unsigned long sizes) {

const char *ptr = NULL;

unsigned short i, j, n, ccitt;

unsigned short c = 0;

unsigned short tabccitt[256];

unsigned short crc = 0;

unsigned short tmp = 0;

unsigned short sc = 0;

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

ccitt = 0;

c = i << 8;

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

if ( (ccitt ^ c) & 0x8000 ){

ccitt = ( ccitt << 1 ) ^ 0x1021;

}

else{

ccitt = ccitt << 1;

}

c = c << 1;

}

tabccitt[i] = ccitt;

}

ptr = src;

crc = 0xFFFF;

if (ptr != NULL) for (n = 0; n < sizes; n++) {

sc = 0X00FF & (unsigned short) *ptr;

tmp = (crc >> 8) ^ sc;

crc = (crc << 8) ^ tabccitt[tmp];

ptr++;

}

return crc;

}

js 实现

/**

*

* 标准CRC16校验码

* @decimalBytes 输入十进制的字节数组

* @return 返回uint16的数字

*

* demo

* const {decimalBytes} = PMQTPTools.transToUTF8('123456789');

* let crc = PMQTPTools.crc16(decimalBytes);

* hexCRC = PMQTPTools.uint16ToHexString(crc);

* console.log(hexCRC); // 29b1

*

*/

static crc16(decimalBytes) {

let crc = 0xFFFF;

let tabccitt = [];

for (let i = 0; i < 256; i++) {

let ccitt = 0;

let c = i << 8;

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

if ((ccitt ^ c) & 0x8000){

ccitt = (ccitt << 1) ^ 0x1021;

}

else{

ccitt = ccitt << 1;

}

c = c << 1;

}

tabccitt.push(this.uint16ToHexString(ccitt));

}

for (let number of decimalBytes) {

const sc = 0x00FF & number;

const index = (0xFFFF) & ((crc >>> 8) ^ sc);

const n = Number.parseInt(tabccitt[index], 16);

crc = (0xFFFF) & ((0xFFFF) &(crc << 8)) ^ ((0xFFFF) & n);

}

return crc;

}

此校验算法,为标准的1021多项式与0xFFFF得到即:crc-ccitt 算法,且统一由c语言翻译而成,实现跨语言可以此crc算法,经过实际项目亲测稳定可用。网上有很多的crc算法实现,但是却基本跨语言及稳定性不太可取,因此总结实现一套统一的验证算法。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值