Converting A String To Hexadecimal In Java

前端 未结 21 2532
青春惊慌失措
青春惊慌失措 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条回答
  •  萌比男神i
    2020-11-22 10:24

    Use DatatypeConverter.printHexBinary():

    public static String toHexadecimal(String text) throws UnsupportedEncodingException
    {
        byte[] myBytes = text.getBytes("UTF-8");
    
        return DatatypeConverter.printHexBinary(myBytes);
    }
    

    Example usage:

    System.out.println(toHexadecimal("Hello StackOverflow"));
    

    Prints:

    48656C6C6F20537461636B4F766572666C6F77
    

    Note: This causes a little extra trouble with Java 9 and newer since the API is not included by default. For reference e.g. see this GitHub issue.

提交回复
热议问题