Converting A String To Hexadecimal In Java

前端 未结 21 2521
青春惊慌失措
青春惊慌失措 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:33

    All answers based on String.getBytes() involve encoding your string according to a Charset. You don't necessarily get the hex value of the 2-byte characters that make up your string. If what you actually want is the equivalent of a hex viewer, then you need to access the chars directly. Here's the function that I use in my code for debugging Unicode issues:

    static String stringToHex(String string) {
      StringBuilder buf = new StringBuilder(200);
      for (char ch: string.toCharArray()) {
        if (buf.length() > 0)
          buf.append(' ');
        buf.append(String.format("%04x", (int) ch));
      }
      return buf.toString();
    }
    

    Then, stringToHex("testing123") will give you:

    0074 0065 0073 0074 0069 006e 0067 0031 0032 0033
    

提交回复
热议问题