Java生成CRC16数据校验码
生活随笔
收集整理的這篇文章主要介紹了
Java生成CRC16数据校验码
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
CRC即循環(huán)冗余校驗(yàn)碼(Cyclic Redundancy Check[1] ?):是數(shù)據(jù)通信領(lǐng)域中最常用的一種查錯(cuò)校驗(yàn)碼,其特征是信息字段和校驗(yàn)字段的長(zhǎng)度可以任意選定。循環(huán)冗余檢查(CRC)是一種數(shù)據(jù)傳輸檢錯(cuò)功能,對(duì)數(shù)據(jù)進(jìn)行多項(xiàng)式計(jì)算,并將得到的結(jié)果附在幀的后面,接收設(shè)備也執(zhí)行類似的算法,以保證數(shù)據(jù)傳輸?shù)恼_性和完整性。
package sk.ann;public class CRCCheck {public static void main(String[] args){String str="Java生成CRC16數(shù)據(jù)校驗(yàn)碼";byte[] data=str.getBytes();System.out.println(CRCCheck.Make_CRC(data));}/*** 計(jì)算產(chǎn)生校驗(yàn)碼* @param data 需要校驗(yàn)的數(shù)據(jù)* @return 校驗(yàn)碼*/public static String Make_CRC(byte[] data) {byte[] buf = new byte[data.length];// 存儲(chǔ)需要產(chǎn)生校驗(yàn)碼的數(shù)據(jù)for (int i = 0; i < data.length; i++) {buf[i] = data[i];}int len = buf.length;int crc = 0xFFFF;//16位for (int pos = 0; pos < len; pos++) {if (buf[pos] < 0) {crc ^= (int) buf[pos] + 256; // XOR byte into least sig. byte of// crc} else {crc ^= (int) buf[pos]; // XOR byte into least sig. byte of crc}for (int i = 8; i != 0; i--) { // Loop over each bitif ((crc & 0x0001) != 0) { // If the LSB is setcrc >>= 1; // Shift right and XOR 0xA001crc ^= 0xA001;} else// Else LSB is not setcrc >>= 1; // Just shift right}}String c = Integer.toHexString(crc);if (c.length() == 4) {c = c.substring(2, 4) + c.substring(0, 2);} else if (c.length() == 3) {c = "0" + c;c = c.substring(2, 4) + c.substring(0, 2);} else if (c.length() == 2) {c = "0" + c.substring(1, 2) + "0" + c.substring(0, 1);}return c;} }總結(jié)
以上是生活随笔為你收集整理的Java生成CRC16数据校验码的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 阅读A Practical Guide
- 下一篇: Centos下机器学习算法Mahout库