package com.zd.base.app; import java.io.ByteArrayOutputStream; /** * hex 转换 * @author dgs * @time 2023-04-11 */ public class HexStrUtils { private static String hexString = "0123456789ABCDEFabcdef"; public static String encode(String str) { byte[] bytes = str.getBytes(); StringBuilder sb = new StringBuilder(bytes.length * 2); //转换hex编码 for (byte b : bytes) { sb.append(Integer.toHexString(b + 0x800).substring(1)); } str = sb.toString(); return str; } //把hex编码转换为string public static String decode(String bytes) { bytes = bytes.toUpperCase(); ByteArrayOutputStream baos = new ByteArrayOutputStream(bytes.length() / 2); // 将每2位16进制整数组装成一个字节 for (int i = 0; i < bytes.length(); i += 2) baos.write((hexString.indexOf(bytes.charAt(i)) << 4 | hexString.indexOf(bytes.charAt(i + 1)))); return new String(baos.toByteArray()); } }