Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bytes not equal after wrap in string [duplicate]

Tags:

java

arrays

I use string for byte array transferring, but found something strange with it. Can somebody explain, why that's happen?

 byte[] bytes1 = new byte[]{-104, 73, 61, -15, -92, 109, 62, -99, 50, 82, 26, 87, 38, 110, -12, 49, -104, 73, 61, -15, -92, 109, 62, -99};
 byte[] bytes2 = new String(bytes1).getBytes();
 //for now bytes2 is equal to: {63, 73, 61, -15, -92, 109, 62, -99, 50, 82, 26, 87, 38, 110, -12, 49, 63, 73, 61, -15, -92, 109, 62, -99}
 System.out.println(Arrays.equals(bytes1, bytes2));//false
 for(int i = 0; i < bytes2.length; i++){
    if(bytes2[i] == 63) {
        bytes2[i] = -104;
    }
 }
 System.out.println(Arrays.equals(bytes1, bytes2));//true

ps bytes1 - this is triple des secret key bytes array. Each time it different, but it fail only in case, if bytes1 contain -104 values. Many thanks.

like image 696
degr Avatar asked Mar 23 '26 04:03

degr


1 Answers

Strings are not byte arrays, byte arrays are not Strings. You can't use one to transfer the other directly.

Strings are logically char arrays. If you want to convert between chars and bytes, you need a character encoding, which specifies the mapping from chars to bytes, and vice versa.

The problem you are having here is that you are using the JVM's default character encoding, and trying to convert byte values which are not supported in that encoding.

If you must store a byte array in a string, you should do something like base64-encode it first.

like image 113
Andy Turner Avatar answered Mar 25 '26 18:03

Andy Turner