简单的写入和读取字节

时间:2012-12-08 19:59:52

标签: java

嘿,我无法弄清楚这里有什么问题。

写入文件:

byte[] dim = new byte[2];
dim[0] = (byte) deImgWidth; // Input 384
dim[1] = (byte) deImgHeight; // Input 216
out.write(dim);

从文件中读取

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

为什么我可以检索相同的deImgHeight值而不是相同的deImgWidth值?

1 个答案:

答案 0 :(得分:6)

384不适合无符号字节而216则不适合。这就是为什么在铸造前者时你必须丢失信息。

Narrowing conversions只保留数字的最低位,因此如果在读取值时执行额外& 0xFF,则可以稍后恢复符号(因为Java对负数使用了两个补码) 。 216 = 0b11011000(适合8位)可以无损转换,但384 = 0b110000000(即9位) - 当你取低8位时,最终得到128位。