Base64 enconding and decoding a byte[] to String gives different results [closed]

so I’m currently trying to save a byte[] to a .txt file and then retrieve it while encoding it and decoding it with Base64 (It is a byte[] with 16 length). I’ve tried this code:

byte[] bytes = new byte[16];
String encoded = Base64.getEncoder().encodeToString(bytes);
bytes = Base64.getDecoder().decode(encoded);

However, when I print bytes before and after encoding the result is never the same, I’ve looked in other forums/questions and I can’t find the issue here, I would appreciate a little help here.


Make sure you are printing the values of the array and not using the toString() method of the array. toString() returns the object’s hash code, which has nothing to do with the values of the array.

If you would like to convert the bytes into a String, use the String(byte[]) constructor, or you can use Java’s Arrays.toString(arr) method to print out the bytes as seen here.

Leave a Reply

Your email address will not be published. Required fields are marked *