Friday, April 5, 2019

Java: Convert byte array to String then back to byte array


The following code works for converting a String to a byte array then back to a String:

String s1 = "Hello World!";
byte[] sb = s1.getBytes();
String s2 = new String(sb);
System.out.println(s1.equals(s2));

The output will be "true".

However, it won't work when using the similar way to convert a byte array to String then back to a byte array.

byte[] b1 = new byte[]{-100, -128, -1, 1, -10, 100, 33, -13, 32, 87};
String bs = new String(b1);
byte[] b2 = bs.getBytes();
System.out.println(Arrays.equals(b1, b2));

The output will be "false".

That is because not every byte can be converted into a character.

One way of doing that would be to convert the byte array to a Base64 encoded string, then you can later decode the string back to a byte array.

byte[] b1 = new byte[] {-100, -128, -1, 1, -10, 100, 33, -13, 32, 87};
String bs = Base64.getEncoder().encodeToString(b1);
byte[] b2 = Base64.getDecoder().decode(bs);
System.out.println(Arrays.equals(b1, b2));

The output will be "true".

The above implementation uses the Base64 class in Java 8. If you are using an earlier version of Java, you need import other implementations of Base64.


No comments:

 
Get This <