[英]What does array of 1's mean in binary when reading
当没有更多字节要读取时,为什么我会得到 1 的 32 位数字? 当我使用 FileInput stream 时。 我不应该得到 EOFException (就像我们得到Object或数据流一样)?
我将演示使用简单的读/写程序。
try {
FileWriter fileWriter = new FileWriter("a.txt");
fileWriter.write('A'); //writes 'A' to file (a.txt)
fileWriter.close();
}catch (IOException ioe){
ioe.printStackTrace();
}
try {
FileInputStream fileInputStream = new FileInputStream("a.txt");
System.out.println(Integer.toBinaryString(fileInputStream.read()));//1000001
System.out.println(Integer.toBinaryString(fileInputStream.read()));//11111111111111111111111111111111
System.out.println(Integer.toBinaryString(fileInputStream.read()));//11111111111111111111111111111111
System.out.println(Integer.toBinaryString(fileInputStream.read()));//11111111111111111111111111111111
}catch (IOException ioe){
ioe.printStackTrace();
}
因此,在每个 read() 中,我得到 4 个字节的 1。 那是无限的。我以为我只会得到字节值,因为 65 是二进制的 1000001。 所以总共1个字节。 这些其他字节从何而来? 它们真的存在吗?
Java 使用称为2 的补码的系统来表示二进制的有符号数。 在这个系统中,数字 -1 用所有位都为 1 的位模式表示。这是因为将 1 添加到所有位都已设置的数字会得到零(感谢overflow )。
所以你观察到的是fileInputStream.read()
返回 -1,这就是它如何指示 state 的“文件结束,没有更多可读取的内容”。
阅读文档! https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/io/FileInputStream.html#read()
read()
Returns:
the next byte of data, or -1 if the end of the file is reached.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.