I got the following code, which converts a char[] to a byte[]:
char[] cPwd = {'p', 'a', 's', 's', 'w', 'o', 'r', 'd'};
byte[] bPwd = new byte[cPwd.length * 2];
ByteBuffer.wrap(bPwd).asCharBuffer().put(cPwd);
What I guessing is that the code above would use the default platform encoding (UTF-8 or 16, i suppose). Right?
How would I make sure the chars from the char[] above use a specific encoding, say UTF-16, as opposed to relying on the default platform encoding?
ps – There is a constraintin my scenario: I am NOT ALLOWED to convert this char[] to a string like in
String str = new String(cPwd, "UTF-16");
Thank you in advance.
Alex.
By the time the VM sees them, the chars that you specify as literals in your code will be 16-bit Unicode characters. The asCharBuffer() method isn’t specified as performing any encoding. In other words, you should effectively get UTF-16, either little or big endian depending on the endianness of your ByteBuffer.
If you want another encoding without going via the String constructor, you can use the CharSet.encode() method: