CRCGenerator.java 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package com.template.common.utils;
  2. public class CRCGenerator {
  3. /**
  4. * 计算CRC16校验码
  5. * @param bytes
  6. * 字节数组
  7. * @return {@link String} 校验码
  8. * @since 1.0
  9. */
  10. public static String getCRC(byte[] bytes) {
  11. // CRC寄存器全为1
  12. int CRC = 0x0000ffff;
  13. // 多项式校验值
  14. int POLYNOMIAL = 0x0000a001;
  15. int i, j;
  16. for (i = 0; i < bytes.length; i++) {
  17. CRC ^= ((int) bytes[i] & 0x000000ff);
  18. for (j = 0; j < 8; j++) {
  19. if ((CRC & 0x00000001) != 0) {
  20. CRC >>= 1;
  21. CRC ^= POLYNOMIAL;
  22. } else {
  23. CRC >>= 1;
  24. }
  25. }
  26. }
  27. // 结果转换为16进制
  28. String result = Integer.toHexString(CRC).toUpperCase();
  29. if (result.length() != 4) {
  30. StringBuffer sb = new StringBuffer("0000");
  31. result = sb.replace(4 - result.length(), 4, result).toString();
  32. }
  33. //高位在前地位在后
  34. //return result.substring(2, 4) + " " + result.substring(0, 2);
  35. // 交换高低位,低位在前高位在后
  36. return result.substring(2, 4) + result.substring(0, 2);
  37. }
  38. /**
  39. * CRC16(modbus)校验
  40. * 获取crc16校验码,参数data中不能有空格
  41. * @param data
  42. * @return
  43. */
  44. public static String getCRC16_Modbus_Str(String data) {
  45. //data = data.replace(" ", "");
  46. int len = data.length();
  47. if (!(len % 2 == 0)) {
  48. return "0000";
  49. }
  50. int num = len / 2;
  51. byte[] para = new byte[num];
  52. for (int i = 0; i < num; i++) {
  53. int value = Integer.valueOf(data.substring(i * 2, 2 * (i + 1)), 16);
  54. para[i] = (byte) value;
  55. }
  56. String data1 = getCRC(para).substring(0,2);
  57. String data2 = getCRC(para).substring(2);
  58. return data1+" "+data2;
  59. }
  60. public static void main(String[] args) {
  61. String data = "01 03 10 00 00 01";
  62. String crc = getCRC16_Modbus_Str(data);
  63. System.out.println("CRC-16: " + crc);
  64. }
  65. }