Hey I cant figure out what is wrong here.
Write to file:
byte[] dim = new byte[2];
dim[0] = (byte) deImgWidth; // Input 384
dim[1] = (byte) deImgHeight; // Input 216
out.write(dim);
Read from File
byte[] file = new byte[(int) f.length()];
FileInputStream fs = new FileInputStream(f);
fs.read(file);
deImgWidth = ((file[0]) & 0xFF); // output 128
deImgHeight = ((file[1]) & 0xFF); // output 216
How come I can retrieve the same deImgHeight value but not the same deImgWidth value?
384 doesn’t fit into an unsigned byte while 216 does. That’s why when casting the former you must lose information.
Narrowing conversions just preserve the lowest bits of a number, so if you do the extra
& 0xFFwhen you read your value, you can later restore the sign (since Java uses two’s complement for negative numbers). 216 = 0b11011000 (fits into 8 bits) can be losslessly transformed, but 384 = 0b110000000 (that’s 9 bits) – when you take the lower 8 bits, you end up with 128.