java - Fast conversion of String to byte[] using UTF-16LE encoding -
i need bytes of millions of string using :
string str="blablabla...."; // utf-16le encoding string extracted db bytes=str.getbytes("utf-16le")
but awfully slow. there custom fast versions of getbytes
don't support utf-16le
. example 1 of them:
// 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]; (int j = 0; j < length; j++) b[j] = (byte) buffer[j]; return b; }
is there similar fast solution convert java string byte array using utf-16le encoding?
this version produce utf16le bytes array:
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]; (int j = 0; j < length; j++) { b[j*2] = (byte) (buffer[j] & 0xff); b[j*2+1] = (byte) (buffer[j] >> 8); } return b; }
tested:
string test = "utf16 Ελληνικά Русский 日本語"; byte[] bytes = test.getbytes("utf-16le"); byte[] bytes2 = getbytesutf16le(test); system.out.println(arrays.equals(bytes, bytes2));
Comments
Post a Comment