CRC16算法之二:CRC16-CCITT-XMODEM算法的java實現

CRC16算法系列文章java

CRC16算法之一:CRC16-CCITT-FALSE算法的java實現

CRC16算法之二:CRC16-CCITT-XMODEM算法的java實現

CRC16算法之三:CRC16-CCITT-MODBUS算法的java實現

 

前言

CRC16算法有不少種,本篇文章會介紹其中的CRC16-CCITT-XMODEM算法算法

 

功能

實現CRC16-CCITT-XMODEM算法數組

支持int、short類型ui

支持選擇數組區域計算spa

實現

  1. package cc.eguid.crc16;
  2.  
  3. /**
  4. * crc16多項式算法
  5. * @author eguid
  6. *
  7. */
  8. public class CRC16 {
  9.  
  10. /**
  11. * CRC16-XMODEM算法(四字節)
  12. * @param bytes
  13. * @return
  14. */
  15. public static int crc16_ccitt_xmodem(byte[] bytes) {
  16. return crc16_ccitt_xmodem(bytes,0,bytes.length);
  17. }
  18.  
  19. /**
  20. * CRC16-XMODEM算法(四字節)
  21. * @param bytes
  22. * @param offset
  23. * @param count
  24. * @return
  25. */
  26. public static int crc16_ccitt_xmodem(byte[] bytes,int offset,int count) {
  27. int crc = 0x0000; // initial value
  28. int polynomial = 0x1021; // poly value
  29. for (int index = offset; index < count; index++) {
  30. byte b = bytes[index];
  31. for (int i = 0; i < 8; i++) {
  32. boolean bit = ((b >> (7 - i) & 1) == 1);
  33. boolean c15 = ((crc >> 15 & 1) == 1);
  34. crc <<= 1;
  35. if (c15 ^ bit)
  36. crc ^= polynomial;
  37. }
  38. }
  39. crc &= 0xffff;
  40. return crc;
  41. }
  42.  
  43. /**
  44. * CRC16-XMODEM算法(兩字節)
  45. * @param bytes
  46. * @param offset
  47. * @param count
  48. * @return
  49. */
  50. public static short crc16_ccitt_xmodem_short(byte[] bytes,int offset,int count) {
  51. return (short)crc16_ccitt_xmodem(bytes,offset,count);
  52. }
  53. /**
  54. * CRC16-XMODEM算法(兩字節)
  55. * @param bytes
  56. * @param offset
  57. * @param count
  58. * @return
  59. */
  60. public static short crc16_ccitt_xmodem_short(byte[] bytes) {
  61. return crc16_ccitt_xmodem_short(bytes,0,bytes.length);
  62. }
  63.  
  64. }

---end---.net

相關文章
相關標籤/搜索