Converting A String To Hexadecimal In Java

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

    The numbers that you encode into hexadecimal must represent some encoding of the characters, such as UTF-8. So first convert the String to a byte[] representing the string in that encoding, then convert each byte to hexadecimal.

    public static String hexadecimal(String input, String charsetName) throws UnsupportedEncodingException {
        if (input == null) throw new NullPointerException();
        return asHex(input.getBytes(charsetName));
    }
    
    private static final char[] HEX_CHARS = "0123456789abcdef".toCharArray();
    
    public static String asHex(byte[] buf)
    {
        char[] chars = new char[2 * buf.length];
        for (int i = 0; i < buf.length; ++i)
        {
            chars[2 * i] = HEX_CHARS[(buf[i] & 0xF0) >>> 4];
            chars[2 * i + 1] = HEX_CHARS[buf[i] & 0x0F];
        }
        return new String(chars);
    }
    

提交回复
热议问题