zoukankan      html  css  js  c++  java
  • CRC16算法之一:CRC16-CCITT-FALSE算法的java实现

    CRC16算法系列文章

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

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

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

    前言

    JDK里包含了CRC32的算法,但是没有CRC16的,网上搜了一堆没有找到想要的,索性自己实现

    注意:CRC16算法分为很多种,本篇文章中,只讲其中的一种:CRC16-CCITT-FALSE算法

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

    功能

    1、支持short类型

    2、支持int类型

    3、支持数组任意区域计算

    实现

    1. /**
    2. * crc16-ccitt-false加密工具
    3. *
    4. * @author eguid
    5. *
    6. */
    7. public class CRC16 {
    8.  
    9. /**
    10. * crc16-ccitt-false加/解密(四字节)
    11. *
    12. * @param bytes
    13. * @return
    14. */
    15. public static int crc16(byte[] bytes) {
    16. return crc16(bytes, bytes.length);
    17. }
    18.  
    19. /**
    20. * crc16-ccitt-false加/解密(四字节)
    21. *
    22. * @param bytes -字节数组
    23. * @return
    24. */
    25. public static int crc16(byte[] bytes, int len) {
    26. int crc = 0xFFFF;
    27. for (int j = 0; j < len; j++) {
    28. crc = ((crc >>> 8) | (crc << 8)) & 0xffff;
    29. crc ^= (bytes[j] & 0xff);// byte to int, trunc sign
    30. crc ^= ((crc & 0xff) >> 4);
    31. crc ^= (crc << 12) & 0xffff;
    32. crc ^= ((crc & 0xFF) << 5) & 0xffff;
    33. }
    34. crc &= 0xffff;
    35. return crc;
    36. }
    37.  
    38. /**
    39. * crc16-ccitt-false加/解密(四字节)
    40. *
    41. * @param bytes
    42. * @return
    43. */
    44. public static int crc16(byte[] bytes, int start, int len) {
    45. int crc = 0xFFFF;
    46. for (; start < len; start++) {
    47. crc = ((crc >>> 8) | (crc << 8)) & 0xffff;
    48. crc ^= (bytes[start] & 0xff);// byte to int, trunc sign
    49. crc ^= ((crc & 0xff) >> 4);
    50. crc ^= (crc << 12) & 0xffff;
    51. crc ^= ((crc & 0xFF) << 5) & 0xffff;
    52. }
    53. crc &= 0xffff;
    54. return crc;
    55. }
    56.  
    57. /**
    58. * crc16-ccitt-false加/解密
    59. *
    60. * @param bytes
    61. * -字节数组
    62. * @return
    63. */
    64. public static short crc16_short(byte[] bytes) {
    65. return crc16_short(bytes, 0, bytes.length);
    66. }
    67.  
    68. /**
    69. * crc16-ccitt-false加/解密(计算从0位置开始的len长度)
    70. *
    71. * @param bytes
    72. * -字节数组
    73. * @param len
    74. * -长度
    75. * @return
    76. */
    77. public static short crc16_short(byte[] bytes, int len) {
    78. return (short) crc16(bytes, len);
    79. }
    80.  
    81. /**
    82. * crc16-ccitt-false加/解密(两字节)
    83. *
    84. * @param bytes
    85. * @return
    86. */
    87. public static short crc16_short(byte[] bytes, int start, int len) {
    88. return (short) crc16(bytes, start, len);
    89. }
    90. }
  • 相关阅读:
    Got05
    Git07
    Git09
    Git11
    Git10
    Git13
    Git12
    Git14
    Listview点击跳转页面
    《三个和尚》观后感
  • 原文地址:https://www.cnblogs.com/eguid/p/9667137.html
Copyright © 2011-2022 走看看