Java:InputStream read()返回一个大于127的字节? [英] Java: InputStream read() returns a byte bigger than 127?

查看:199
本文介绍了Java:InputStream read()返回一个大于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.

这是将读取字节转换为 int

(因此negatif 字节成为positif int

如果是这样,我可以通过将 int 转换为a来执行相同的操作(使用 OutputStream byte

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?

谢谢,

Martijn

Thanks,
Martijn

推荐答案

实际上读取返回一个整数..

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到
255范围内的int。如果没有字节可用,因为流的末尾已达到
,则返回值-1。 / p>

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 couldn' t用作流值的结尾。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆