Java:InputStream read() 返回一个大于 127 的字节? [英] Java: InputStream read() returns a byte bigger than 127?
问题描述
我有这个代码:
InputStream is = socket.getInputStream();
int b;
while ((b = is.read()) != -1)
{
System.out.println(b);
}
一个字节,它的范围是 -128
直到 +127
.
但是打印的字节之一是210
.
A byte its range is -128
until +127
.
But one of the printed bytes is 210
.
这是将读取的 byte
转换为 int
的结果吗?
(所以否定 byte
变成了 positif int
)
如果是这样,我可以通过将 int
转换为 byte
来做同样的事情(使用 OutputStream
)吗?
Is this the result of converting the read byte
to an int
?
(So that the negatif byte
becomes a positif int
)
If so, can I do the same (with an OutputStream
) by converting an int
to a byte
?
谢谢,
马丁
推荐答案
实际上read
返回的是一个整数..
Actually read
returns an integer..
public abstract int read() throws IOException
因此通过将其存储在 int 中,它被隐式转换为无符号字节.
so it's implictly casted to be unsigned byte by storing it in an int.
如文档中所述:
读取下一个字节的数据输入流.值字节是以 0 到范围内的 int 形式返回255.如果因为流的末尾已经没有字节可用达到,返回值 -1.
Reads the next byte of data from the input stream. The value byte is returned as an int in the range 0 to 255. If no byte is available because the end of the stream has been reached, the value -1 is returned.
考虑这样一个事实,如果它是一个有符号字节,则 -1
不能用作流值的结尾.
Think about the fact that if it's a signed byte then -1
couldn't be used as end of stream value.
对于 OutputStream
你有
public abstract void write(int b) throws IOException
并且如文档实现所述,将采用传递的整数的 8 个低位位..
and as stated by documentation implementation will take 8 low order bits of the integer passed..
这篇关于Java:InputStream read() 返回一个大于 127 的字节?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!