Does anyone know how to take a byte[] to a String and back to a byte[] and get the same bytes you started with? I figured this would just work signed bytes not with standing. But it turns out the String(byte[]) converts negative bytes to unexpected characters, unexpected because I don’t know what its doing. Here an example:
public class Test {
public static void main(String[] args) {
try {
byte[] b = new byte[] {0, -127, 0, 12};
String s = new String(b, "ascii");
printBytes(b);
System.out.println("\ntest:" + s + ":");
printBytes(s.getBytes("ascii"));
} catch(Exception e) {
e.printStackTrace();
}
}
private static void printBytes(byte[] bytes) {
System.out.print("bytes:");
for(byte b : bytes) {
System.out.format("%d,", b);
}
}
}
The output is:
bytes:bytes:0,-127,0,12,
test: {unprintable characters}
bytes:bytes:0,63,0,12,
So -127 goes to 63, that makes not sense. Does anyone have any ideas on how to go about doing this? Or what a good google search phrase would be?