java api crc_CRC16算法Java实现

模仿C++代码改写的Java实现

public class CRC16 {

private short[] crcTable = new short[256];

private int gPloy = 0x1021; // 生成多项式

public CRC16() {

computeCrcTable();

}

private short getCrcOfByte(int aByte) {

int value = aByte << 8;

for (int count = 7; count >= 0; count--) {

if ((value & 0x8000) != 0) { // 高第16位为1,可以按位异或

value = (value << 1) ^ gPloy;

} else {

value = value << 1; // 首位为0,左移

}

}

value = value & 0xFFFF; // 取低16位的值

return (short)value;

}

/*

* 生成0 - 255对应的CRC16校验码

*/

private void computeCrcTable() {

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

crcTable[i] = getCrcOfByte(i);

}

}

public short getCrc(byte[] data) {

int crc = 0;

int length = data.length;

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

crc = ((crc & 0xFF) << 8) ^ crcTable[(((crc & 0xFF00) >> 8) ^ data[i]) & 0xFF];

}

crc = crc & 0xFFFF;

return (short)crc;

}

}

public final class CodecUtil {

static CRC16 crc16 = new CRC16();

private CodecUtil() {

}

public static byte[] short2bytes(short s) {

byte[] bytes = new byte[2];

for (int i = 1; i >= 0; i--) {

bytes[i] = (byte)(s % 256);

s >>= 8;

}

return bytes;

}

public static short bytes2short(byte[] bytes) {

short s = (short)(bytes[1] & 0xFF);

s |= (bytes[0] << 8) & 0xFF00;

return s;

}

/*

* 获取crc校验的byte形式

*/

public static byte[] crc16Bytes(byte[] data) {

return short2bytes(crc16Short(data));

}

/*

* 获取crc校验的short形式

*/

public static short crc16Short(byte[] data) {

return crc16.getCrc(data);

}

public static void main(String[] args) {

byte[] test = new byte[] {0, 1, 2, 3, 4};

byte[] crc = crc16Bytes(test);

byte[] testc = new byte[test.length + 2];

for (int i = 0; i < test.length; i++) {

testc[i] = test[i];

}

testc[test.length] = crc[0];

testc[test.length + 1] = crc[1];

System.out.println(crc16Short(testc));

}

}

分享到:

18e900b8666ce6f233d25ec02f95ee59.png

72dd548719f0ace4d5f9bca64e1d7715.png

2009-01-17 15:52

浏览 25483

论坛回复 / 浏览 (3 / 7074)

评论

3 楼

379548695

2009-11-18

能帮我把这个改成java的吗

#include /* CRC-8 按位计算实现 */

unsigned

int cal_crc(unsigned char *ptr, unsigned char len) {

unsigned char i;

unsigned char crc=0;

while(len--!=0)

{

for(i=0x80; i!=0; i/=2)

{

if((crc&0x80)!=0)

{crc*=2; crc^=0x1f;} /* 余式CRC乘以2再求CRC */

else crc*=2;

if((*ptr&i)!=0) crc^=0x1f; /* 再加上本位的CRC */

}

ptr++;

}

return(crc);

}

int main()

{

char *a="410400110012";

printf("%d\n",cal_crc(a,strlen(a))) ;

getch();

}

2 楼

sunzhenyuan

2009-02-03

sdh5724 写道

好像现在JAVA API已经有了吧。 :)

呵呵,API里的那个不是完整的实现。

1 楼

sdh5724

2009-01-17

好像现在JAVA API已经有了吧。 :)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值