CRC16算法之三:CRC16-CCITT-MODBUS算法的java实现

CRC16算法系列文章

CRC16算法之一:CRC16-CCITT-FALSE算法的java实现

CRC16算法之二:CRC16-CCITT-XMODEM算法的java实现

CRC16算法之三:CRC16-CCITT-MODBUS算法的java实现

 

 

功能

实现CRC16-CCITT-MODBUS算法

支持int、short类型

支持选择数组区域计算

实现

  1. /**
  2. * crc16_ccitt_modbus算法(四字节)友情提示:做好自己!--eguid博客地址:http://blog.csdn.net/eguid_1
  3. * @param buf
  4. * @param offset
  5. * @param length
  6. * @return
  7. */
  8. public static int crc16_ccitt_modbus(byte[] buf,int offset, int length) {
  9. int i, j;
  10. int c, crc = 0xFFFF;
  11. for (i = offset; i < length; i++) {
  12. c = buf[i] & 0x00FF;
  13. crc ^= c;
  14. for (j = 0; j < 8; j++) {
  15. if ((crc & 0x0001) != 0) {
  16. crc >>= 1;
  17. crc ^= 0xA001;
  18. } else
  19. crc >>= 1;
  20. }
  21. }
  22. return crc;
  23. }
  24.  
  25. /**
  26. * crc16_ccitt_modbus算法(四字节)
  27. * @param buf
  28. * @return
  29. */
  30. public static int crc16_ccitt_modbus(byte[] buf) {
  31. return crc16_ccitt_modbus(buf,0,buf.length);
  32. }
  33.  
  34.  
  35. /**
  36. * crc16_ccitt_modbus算法(两字节)
  37. * @param buf
  38. * @param offset
  39. * @param length
  40. * @return
  41. */
  42. public static int crc16_ccitt_modbus_short(byte[] buf,int offset, int length) {
  43. return (short)crc16_ccitt_modbus(buf,offset,length);
  44. }
  45.  
  46. /**
  47. * crc16_ccitt_modbus算法(两字节)
  48. * @param buf
  49. * @return
  50. */
  51. public static int crc16_ccitt_modbus_short(byte[] buf) {
  52. return (short)crc16_ccitt_modbus(buf,0,buf.length);
  53. }

转载于:https://www.cnblogs.com/eguid/p/9667144.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值