Converting A String To Hexadecimal In Java

前端 未结 21 2738
青春惊慌失措
青春惊慌失措 2020-11-22 09:55

I am trying to convert a string like \"testing123\" into hexadecimal form in java. I am currently using BlueJ.

And to convert it back, is it the same thing except b

21条回答
  •  面向向阳花
    2020-11-22 10:28

    Here are some benchmarks comparing different approaches and libraries. Guava beats Apache Commons Codec at decoding. Commons Codec beats Guava at encoding. And JHex beats them both for decoding and encoding.

    JHex example

    String hexString = "596f752772652077656c636f6d652e";
    byte[] decoded = JHex.decodeChecked(hexString);
    System.out.println(new String(decoded));
    String reEncoded = JHex.encode(decoded);
    

    Everything is in a single class file for JHex. Feel free to copy paste if you don't want yet another library in your dependency tree. Also note, it is only available as Java 9 jar until I can figure out how to publish multiple release targets with Gradle and the Bintray plugin.

提交回复
热议问题