Search code examples
javautf-16

Java How to convert string to UTF-16BE from request.getParameter() function?


I am now using the following code but it doesn't performs well. Only few words can be convert.

public String convert(String big5) throws java.io.UnsupportedEncodingException {
    byte[] tmp = big5.getBytes( "UTF-16BE");
    String result = "";
    for (int i=0; i<tmp.length; i++) {
        result += Integer.toHexString(((int)tmp[i]));
    }

    return result.toUpperCase();
}

Solution

  • Does this work for you?

    result += Integer.toHexString(((int)(tmp[i] & 0xFF)));
    

    To treat a byte value as unsigned, you need to do a bitwise & with 0xFF.

    Hope this helps.