How to convert Strings to and from UTF8 byte arrays in Java

前端 未结 13 2365
终归单人心
终归单人心 2020-11-22 13:05

In Java, I have a String and I want to encode it as a byte array (in UTF8, or some other encoding). Alternately, I have a byte array (in some known encoding) and I want to c

13条回答
  •  借酒劲吻你
    2020-11-22 13:39

    If you are using 7-bit ASCII or ISO-8859-1 (an amazingly common format) then you don't have to create a new java.lang.String at all. It's much much more performant to simply cast the byte into char:

    Full working example:

    for (byte b : new byte[] { 43, 45, (byte) 215, (byte) 247 }) {
        char c = (char) b;
        System.out.print(c);
    }
    

    If you are not using extended-characters like Ä, Æ, Å, Ç, Ï, Ê and can be sure that the only transmitted values are of the first 128 Unicode characters, then this code will also work for UTF-8 and extended ASCII (like cp-1252).

提交回复
热议问题