Converting char array into byte array and back again
Conversion between char and byte is character set encoding and decoding.I prefer to make it as clear as possible in code. It doesn't really mean extra code volume:
Charset latin1Charset = Charset.forName("ISO-8859-1"); charBuffer = latin1Charset.decode(ByteBuffer.wrap(byteArray)); // also decode to String byteBuffer = latin1Charset.encode(charBuffer); // also decode from String
Aside:
java.nio classes and java.io Reader/Writer classes use ByteBuffer & CharBuffer (which use byte[] and char[] as backing arrays). So often preferable if you use these classes directly. However, you can always do:
byteArray = ByteBuffer.array(); byteBuffer = ByteBuffer.wrap(byteArray); byteBuffer.get(byteArray); charBuffer.put(charArray); charArray = CharBuffer.array(); charBuffer = ByteBuffer.wrap(charArray); charBuffer.get(charArray); charBuffer.put(charArray);
The problem is your use of the String(byte[])
constructor, which uses the platform default encoding. That's almost never what you should be doing - if you pass in "UTF-16" as the character encoding to work, your tests will probably pass. Currently I suspect that passwordBytes1AsString
and passwordBytes2AsString
are each 16 characters long, with every other character being U+0000.
Original Answer
public byte[] charsToBytes(char[] chars){ Charset charset = Charset.forName("UTF-8"); ByteBuffer byteBuffer = charset.encode(CharBuffer.wrap(chars)); return Arrays.copyOf(byteBuffer.array(), byteBuffer.limit()); } public char[] bytesToChars(byte[] bytes){ Charset charset = Charset.forName("UTF-8"); CharBuffer charBuffer = charset.decode(ByteBuffer.wrap(bytes)); return Arrays.copyOf(charBuffer.array(), charBuffer.limit()); }
Edited to use StandardCharsets
public byte[] charsToBytes(char[] chars){ final ByteBuffer byteBuffer = StandardCharsets.UTF_8.encode(CharBuffer.wrap(chars)); return Arrays.copyOf(byteBuffer.array(), byteBuffer.limit());}public char[] bytesToChars(byte[] bytes){ final CharBuffer charBuffer = StandardCharsets.UTF_8.decode(ByteBuffer.wrap(bytes)); return Arrays.copyOf(charBuffer.array(), charBuffer.limit()); }
Here is a JavaDoc page for StandardCharsets.Note this on the JavaDoc page:
These charsets are guaranteed to be available on every implementation of the Java platform.