JAVA: Convert Byte[] to Char[] and other way.

Started by
5 comments, last by snk_kid 18 years, 4 months ago
Hi there. Dunno if this is correct forum to post this on, but is it possible in java to convert a byte[] to char[] and other way around. This is for a server. i got this code

              byte[] decrypt = new byte[length - 2];
                char[] data = new char[length - 2];
        
                System.arraycopy(incoming, 2, data, 0, decrypt.length);
    
                Encryption.prepareKeys(client);
                //Decrypt the data
                for(int i = 0; i < 1; ++i)
                    data = Encryption.decrypt(data);

                System.arraycopy(decrypt, 0, data, 0, decrypt.length);


incoming is also a byte[] buffer it copy incomming to data, decrypt data, copy data to decrypt, then the decryptet data should be in decrypt. it gives me this error tho : Server thread[C] started java.lang.ArrayStoreException at java.lang.System.arraycopy(Native Method) at server.loginserver.ClientThread.run(ClientThread.java:143) Server thread[C] stopped im using jdk 1.5.0 update 6 and Eclipse as dev tool. Thanks.
Advertisement
char and byte are different things in Java. char can hold all unicode chars which means it has to have >16 bits.

Quote:arraycopy throws a ArrayStoreException when:
-The src argument and dest argument refer to arrays whose component types are different primitive types.
You want to look into the classes Charset, CharsetDecoder, CharsetEncoder to convert to/from a character buffer and a byte buffer.
Maybe an exsample on how to do it ?

Im still a bit lost :o
tryed this:

				byte[] decrypt = new byte[length - 2];				char[] data = new char[length - 2];				System.arraycopy(incoming, 2, decrypt, 0, decrypt.length);				_char.newDecoder().decode(decrypt, data, true);


however it says :

The method decode(ByteBuffer, CharBuffer, boolean) in the type CharsetDecoder is not applicable
for the arguments (byte[], char[], boolean)
found a sollution, takes a bit more ram, but o well.
Quote:Original post by NightMarez
The method decode(ByteBuffer, CharBuffer, boolean) in the type CharsetDecoder is not applicable for the arguments (byte[], char[], boolean)


The point is you use the "array" method to get the underlying charater/byte array.

This topic is closed to new replies.

Advertisement