java中十六进制转ASCII编码

将字符串转换成十六进制

  1. 将每个字符串转换成数组
  2. 将数组中字符转换成整型
  3. 使用Integer.toHexString()方法转换成十六进制
1
2
3
4
5
6
7
8
9
private static String asciiToHex(String asciiStr) {
char[] chars = asciiStr.toCharArray();
StringBuilder hex = new StringBuilder();
for (char ch : chars) {
hex.append(Integer.toHexString((int) ch));
}

return hex.toString();
}
  1. 截断一个十六进制为两个字符组
  2. 使用Integer.parseInt(hex, 16)方法强转字符
  3. 把每个字符添加的StringBuilder
1
2
3
4
5
6
7
8
9
10
private static String hexToAscii(String hexStr) {
StringBuilder output = new StringBuilder("");

for (int i = 0; i < hexStr.length(); i += 2) {
String str = hexStr.substring(i, i + 2);
output.append((char) Integer.parseInt(str, 16));
}

return output.toString();
}

测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@Test
public static void whenHexToAscii() {
String asciiString = "www.matosiki.com";
String hexEquivalent =
"3737373737373265363236313635366336343735366536373265363336663664";

assertEquals(asciiString, hexToAscii(hexEquivalent));
}

@Test
public static void whenAsciiToHex() {
String asciiString = "www.matosiki.com";
String hexEquivalent =
"3737373737373265363236313635366336343735366536373265363336663664";

assertEquals(hexEquivalent, asciiToHex(asciiString));
}

总结: 以上同16进制与ascii码相互转换.

分享到