使用UTF-16LE编码将String快速转换为byte []

时间:2015-05-14 07:01:19

标签: java android optimization encoding character-encoding

我需要使用这个来获取数百万字符串的字节:

String str="blablabla...."; // some UTF-16LE encoding string extracted from DB
bytes=str.getBytes("UTF-16LE")

但这非常缓慢。有getBytes的自定义快速版本,但它们不支持UTF-16LE。例如,这是其中之一:

// http://stackoverflow.com/questions/12239993/why-is-the-native-string-getbytes-method-slower-than-the-custom-implemented-getb
private static byte[] getBytesFast(String str) {
    final char buffer[] = new char[str.length()];
    final int length = str.length();
    str.getChars(0, length, buffer, 0);
    final byte b[] = new byte[length];
    for (int j = 0; j < length; j++)
        b[j] = (byte) buffer[j];
    return b;
}

是否有使用UTF-16LE编码将Java字符串转换为字节数组的类似快速解决方案?

1 个答案:

答案 0 :(得分:3)

此版本将生成UTF16LE字节数组:

private static byte[] getBytesUTF16LE(String str) {
    final int length = str.length();
    final char buffer[] = new char[length];
    str.getChars(0, length, buffer, 0);
    final byte b[] = new byte[length*2];
    for (int j = 0; j < length; j++) {
        b[j*2] = (byte) (buffer[j] & 0xFF);
        b[j*2+1] = (byte) (buffer[j] >> 8);
    }
    return b;
}

测试:

String test = "UTF16 Ελληνικά Русский 日本語";
byte[] bytes = test.getBytes("UTF-16LE");
byte[] bytes2 = getBytesUTF16LE(test);
System.out.println(Arrays.equals(bytes, bytes2));