0

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

写入文件:

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 值?

4

1 回答 1

6

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

缩小转换只保留数字的最低位,因此如果您在& 0xFF读取值时执行额外操作,您可以稍后恢复符号(因为 Java 使用二进制补码表示负数)。216 = 0b11011000(适合 8 位)可以进行无损转换,但是 384 = 0b110000000(即 9 位) - 当你取低 8 位时,你最终得到 128。

于 2012-12-08T20:13:17.630 回答