HexUtils.java 956 B

123456789101112131415161718192021222324252627
  1. package com.huimv.admin.jinghongtimer;
  2. public class HexUtils {
  3. // 16进制字符串转字节数组(例如:"A1B2" → byte[]{0xA1, 0xB2})
  4. public static byte[] hexStringToBytes(String hex) {
  5. hex = hex.replaceAll("\\s", ""); // 移除空格
  6. if (hex.length() % 2 != 0) {
  7. throw new IllegalArgumentException("Hex string length must be even");
  8. }
  9. byte[] bytes = new byte[hex.length() / 2];
  10. for (int i = 0; i < hex.length(); i += 2) {
  11. String byteStr = hex.substring(i, i + 2);
  12. bytes[i/2] = (byte) Integer.parseInt(byteStr, 16);
  13. }
  14. return bytes;
  15. }
  16. // 字节数组转16进制字符串(带空格分隔)
  17. public static String bytesToHexString(byte[] bytes) {
  18. StringBuilder sb = new StringBuilder();
  19. for (byte b : bytes) {
  20. sb.append(String.format("%02X ", b));
  21. }
  22. return sb.toString().trim();
  23. }
  24. }