How to get hex out of the string?

92 views Asked by At

I am reading a text file in Java line by line. For debugging purpose, I would like to get the hex value of the string to check how it is encoded.

For example:

This is my text-file:

äpple
tree

This is how I read the file:

inputCharset = Charset.forName("ISO-8859-1")
BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(fi), inputCharset));
while ( in.ready() ) {
      String row = in.readLine();
      System.out.println(row + " = " + toHex(row));
}

The result must be for first line

äpple = E4 70 70 6C 65

How can I convert the chars of the string to the appropriate hex value?

3

There are 3 answers

0
BambooleanLogic On

In order to get the binary representation of the string, you use the getBytes method on the string:

byte[] bytes = row.getBytes("ISO-8859-1");

Once you have a raw byte array, there are various ways to display it as a hex string.

3
Chaosfire On

Since you have already read the line as a string, the easiest way should be to use String.codePoints() to get an IntStream.

String hexedRow = row.codePoints()
  .mapToObj(Integer::toHexString)
  .map(String::toUpperCase)
  .collect(Collectors.joining(" "));
System.out.println(row + " = " + hexedRow);

For äpple prints:

äpple = E4 70 70 6C 65

If you are not yet on java 9, you can simply iterate the characters and cast them to int before 'hex'-ing them.

0
k314159 On

For something with good flexibility, you can use the new HexFormat class introduced in Java 17:

var inputCharset = StandardCharsets.ISO_8859_1;
var hexFormat = HexFormat.ofDelimiter(" ").withUpperCase();
try (var in = Files.newBufferedReader(Path.of(fi), inputCharset))) {
    String row;
    while ((row = in.readLine()) != null) {
        System.out.println(row + " = " + hexFormat.formatHex(row.getBytes(inputCharset));
    }
}