DataUtils.java 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. package com.mes.util;
  2. public class DataUtils {
  3. // 将16进制字符串转化为byte数组
  4. public static byte[] hexStringToByteArray(String s) {
  5. s = s.replace(" ", "");
  6. int len = s.length();
  7. byte[] data = new byte[len / 2];
  8. for (int i = 0; i < len; i += 2) {
  9. data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
  10. + Character.digit(s.charAt(i + 1), 16));
  11. }
  12. return data;
  13. }
  14. public static int getBit(int data, int index) {
  15. return (data >> index) & 1;
  16. }
  17. public static int bytesToInt(byte[] data) {
  18. int a = 0;
  19. for (int i = 0; i < data.length; i++) {
  20. a = a | (data[i] & 0xFF) << (8 * i);
  21. }
  22. return a;
  23. }
  24. // 将一个byte值转换成16进制形式的字符串
  25. public static String byteToHexString(byte b) {
  26. // 得到高4位和低4位的数字
  27. int high = (b & 0xF0) >>> 4; // 高4位
  28. int low = b & 0x0F; // 低4位
  29. // 将高4位和低4位转换为16进制字符
  30. return hexChar(high) + String.valueOf(hexChar(low));
  31. }
  32. public static String CRC16(String input) {
  33. byte[] bytes = hexStringToByteArray(input);
  34. // 初始化CRC寄存器
  35. int crc = 0xFFFF;
  36. for (byte b : bytes) {
  37. // 更新CRC寄存器
  38. crc ^= (b & 0xFF);
  39. for (int i = 0; i < 8; i++) {
  40. if ((crc & 0x0001) != 0) {
  41. crc >>= 1;
  42. crc ^= 0xA001;
  43. } else {
  44. crc >>= 1;
  45. }
  46. }
  47. }
  48. // 获取CRC16结果的高位和低位
  49. byte high = (byte) ((crc >> 8) & 0xFF);
  50. byte low = (byte) (crc & 0xFF);
  51. // 将CRC16结果添加到原始字符串后面
  52. return input + " " + byteToHexString(low) + " " + byteToHexString(high);
  53. }
  54. // 把int数据转化为Word,一个Word有两字节, 且低位在前、高位在后
  55. public static String intToWord(int n) {
  56. byte b1 = (byte) (n & 0xFF);
  57. byte b2 = (byte) ((n >> 8) & 0xFF);
  58. String s1 = byteToHexString(b1);
  59. String s2 = byteToHexString(b2);
  60. return s1 + " " + s2;
  61. }
  62. // 辅助方法:根据数字返回对应的16进制字符
  63. private static char hexChar(int n) {
  64. if (n >= 0 && n <= 9) {
  65. return (char) ('0' + n);
  66. } else if (n >= 10 && n <= 15) {
  67. return (char) ('A' + (n - 10));
  68. }
  69. throw new IllegalArgumentException("转换为十六进制字符的值无效: " + n);
  70. }
  71. }