繁体   English   中英

简单的读写字节

[英]Simple writing and reading bytes

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

写入文件:

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM