HexStrUtils.java 1.0 KB

1234567891011121314151617181920212223242526272829303132333435
  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 static String hexString = "0123456789ABCDEFabcdef";
  10. public static String encode(String str) {
  11. byte[] bytes = str.getBytes();
  12. StringBuilder sb = new StringBuilder(bytes.length * 2);
  13. //转换hex编码
  14. for (byte b : bytes) {
  15. sb.append(Integer.toHexString(b + 0x800).substring(1));
  16. }
  17. str = sb.toString();
  18. return str;
  19. }
  20. //把hex编码转换为string
  21. public static String decode(String bytes) {
  22. bytes = bytes.toUpperCase();
  23. ByteArrayOutputStream baos = new ByteArrayOutputStream(bytes.length() / 2);
  24. // 将每2位16进制整数组装成一个字节
  25. for (int i = 0; i < bytes.length(); i += 2)
  26. baos.write((hexString.indexOf(bytes.charAt(i)) << 4 | hexString.indexOf(bytes.charAt(i + 1))));
  27. return new String(baos.toByteArray());
  28. }
  29. }