Wednesday, May 30, 2012

Convert char[] array to byte[] array in Java

I have spent a few hours trying to convert a char[] returned by a JPasswordField into a byte[] that I can encrypt in Java. Here is the conversion code that I finally came up with :
      public void testArrayConversionJapanese() {  
           String hello = new String("こんにちは世界");  
           char[] charArray = hello.toCharArray();  
           byte[] byteArray = new byte[charArray.length*2];  
           for (int i=0; i < charArray.length; i++) {  
                byteArray[i*2] = (byte) ((charArray[i] & 0xFF00) >> 8);  
                byteArray[i*2+1] = (byte) (charArray[i] & 0x00FF);  
           }  
           char[] chars2 = new char[byteArray.length/2];  
           for(int i=0; i < chars2.length; i++) {  
                //bytes must be & with 0x00FF to convert negative values into unsigned positive values  
                chars2[i] = (char) (((byteArray[i*2]&0x00FF) << 8) + (byteArray[i*2+1]&0x00FF));  
           }  
           String hello2 = new String(chars2);  
           assertEquals(hello, hello2);  
      }  
As you can see above, I have used basic array and shift operations for the conversion. This is much more efficient than using java.lang.Character, String and Byte classes to do the conversions.

1 comment:

Unknown said...

Thanks for the post.

As a matter of fact, I am looking a solution for coversion between char[] & byte[] without passing through creating (even implictily) a heap object (such as new String, nex BufferArray, new ByteArray, etc).

Codes from the first part works fine: bye[] toByteArray(char[] chars);
But for the second part, I got a question: char[] toCharArray(byte[] bytes)
in this line, char[] chars2 = new char[byteArray.length/2]
What happens if the input byteArray length is not multiple of two? do we loose a byte ?
I am talking about the general case of converting any byte[] to char[], bytes might not comming from a String.