HexStrUtils.java 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. package com.zd.base.app;
  2. import java.io.ByteArrayOutputStream;
  3. /**
  4. * hex 转换
  5. * @author dgs
  6. * @time 2023-04-11
  7. */
  8. public class HexStrUtils {
  9. private HexStrUtils(){}
  10. private static String hexString = "0123456789ABCDEFabcdef";
  11. public static String encode(String str) {
  12. byte[] bytes = str.getBytes();
  13. StringBuilder sb = new StringBuilder(bytes.length * 2);
  14. //转换hex编码
  15. for (byte b : bytes) {
  16. sb.append(Integer.toHexString(b + 0x800).substring(1));
  17. }
  18. str = sb.toString();
  19. return str;
  20. }
  21. //把hex编码转换为string
  22. public static String decode(String bytes) {
  23. bytes = bytes.toUpperCase();
  24. ByteArrayOutputStream baos = new ByteArrayOutputStream(bytes.length() / 2);
  25. // 将每2位16进制整数组装成一个字节
  26. for (int i = 0; i < bytes.length(); i += 2)
  27. baos.write((hexString.indexOf(bytes.charAt(i)) << 4 | hexString.indexOf(bytes.charAt(i + 1))));
  28. return new String(baos.toByteArray());
  29. }
  30. }