Convert Hex to ASCII in Java – 在Java中把十六进制转换为ASCII

最后修改: 2016年 11月 4日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this quick article, we’re going to do some simple conversions between the Hex and ASCII formats.

在这篇快速文章中,我们将在Hex和ASCII格式之间做一些简单的转换。

In a typical use case, the Hex format can be used to write down very large integer values in a compact form. For example, AD45 is shorter than its decimal equivalent 44357 and as values increase the difference in length becomes even more pronounced.

在一个典型的使用案例中,Hex格式可以用来以紧凑的形式写下非常大的整数值。例如,AD45比它的十进制等价物44357要短,随着数值的增加,长度的差异变得更加明显。

2. ASCII to Hex

2.ASCII转16进制

Now, let’s look at our options to convert ASCII values to Hex:

现在,让我们看看将ASCII值转换为Hex的选项。

  1. Convert String to char array
  2. Cast each char to an int
  3. Use Integer.toHexString() to convert it to Hex

Here’s a quick example how we can achieve above steps:

下面是一个快速的例子,我们如何实现上述步骤。

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();
}

3. Hex to ASCII Format

3.十六进制到ASCII格式

Similarly, let’s do a Hex to ASCII format conversion in three steps :

同样地,让我们分三步进行Hex到ASCII格式的转换。

  1. Cut the Hex value in 2 char groups
  2. Convert it to base 16 Integer using Integer.parseInt(hex, 16) and cast to char
  3. Append all chars in a StringBuilder

Let’s look at an example how we can achieve above steps:

让我们看一个例子,我们如何实现上述步骤。

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();
}

4. Test

4.测试

Finally, using these methods, let’s do a quick test :

最后,使用这些方法,让我们做一个快速测试。

@Test
public static void whenHexToAscii() {
    String asciiString = "www.baeldung.com";
    String hexEquivalent = 
      "7777772e6261656c64756e672e636f6d";

    assertEquals(asciiString, hexToAscii(hexEquivalent));
}

@Test
public static void whenAsciiToHex() {
    String asciiString = "www.baeldung.com";
    String hexEquivalent = 
      "7777772e6261656c64756e672e636f6d";

    assertEquals(hexEquivalent, asciiToHex(asciiString));
}

5. Conclusion

5.总结

To conclude, we looked at the simplest ways of converting between ASCII and Hex using Java.

最后,我们看了用Java在ASCII和Hex之间转换的最简单方法。

The implementation of all these examples and code snippets can be found in the github project – simply import the project and run as it is.

所有这些例子和代码片段的实现都可以在github项目中找到–只需导入该项目并按原样运行。