String toByte and reverse, not bijective if bytes are modified
arrays, java
Solution
when you use the constructor String(byte[]), it doesn't necesarily takes one letter per byte, it takes the default charset; if it is, say, UTF-8, then the constructor will try to decode some chars from two or three bytes rather than just one.
As you are using bit-complement to transform byte by byte, the result could be different when you apply the default charset.
If you are using only ASCII chars, you could try this version of your function:
// ONLY if you use ASCII as Charset
public static String convert(String s) {
Charset ASCII = Charset.forName("ASCII");
byte[] bytes = s.getBytes(ASCII);
byte[] convert = new byte[bytes.length];
for (int i = 0; i < bytes.length; i++) {
convert[i] = (byte) (~bytes[i] & 0x7F);
}
return new String(convert, ASCII);
}
Problem
Following Code changes every byte of a string and creates a new string. ``` public static String convert(String s) { byte[] bytes = s.getBytes(); byte[] convert = new byte[bytes.length]; for (int i = 0; i < bytes.length; i++) { convert[i] = (byte) ~bytes[i]; } return new String(convert); } ``` Question: Why is convert() not bijective? ``` convert(convert("Test String")).equals("Test String") === false ```