Java 实现 16 进制和字符串的相互转化 发表于 2013-07-26 | 阅读次数: 12345678910111213141516171819202122232425262728293031323334353637import java.io.ByteArrayOutputStream;import java.io.UnsupportedEncodingException;public class TestHexAndString { /* 16 进制数字字符集 */ private static String hexString = "0123456789ABCDEF"; // 此处不可随意改动 /* 将字符串编码成 16 进制数字 */ public static String encode(String str) throws UnsupportedEncodingException { // 根据默认编码获取字节数组 byte[] bytes = str.getBytes("GBK"); StringBuilder sb = new StringBuilder(bytes.length * 2); // 将字节数组中每个字节拆解成 2 位 16 进制整数 for (int i = 0; i < bytes.length; i++) { sb.append(hexString.charAt((bytes[i] & 0xf0) >> 4)); sb.append(hexString.charAt((bytes[i] & 0x0f) >> 0)); } return sb.toString(); } /* 将 16 进制数字解码成字符串 */ public static String decode(String bytes) throws UnsupportedEncodingException { 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(), "GBK"); } public static void main(String[] args) throws Exception { System.out.println(encode("测试转化为 16 进制")); // 测试将字符串转化为 16 进制 System.out.println(decode("B2E2CAD4D7AABBAFCEAA3136BDF8D6C6")); // 反向测试将 16 进制转化为字符串 } } 相关文章 二叉树的四种遍历方式(Java 实现) Tomcat:Invalid character found in the request target. The valid characters are defined in RFC 7230 and RFC 3986 一种后台管理系统接口防重复点击实现方式 使用 Guava 的 ImmutableMap 构建不可变的 Map 使用 Embed Tomcat 嵌入式启动 JavaWeb 项目 本文链接: https://zhangzw.com/posts/20130726.html 版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-ND 许可协议。转载请注明出处!