Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
610 views
in Technique[技术] by (71.8m points)

io - Java: InputStream read() returns a byte bigger than 127?

I've this code:

InputStream is = socket.getInputStream();
int b;
while ((b = is.read()) != -1)
{
   System.out.println(b);
}

A byte its range is -128 until +127.
But one of the printed bytes is 210.

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?

Thanks,
Martijn

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Actually read returns an integer..

public abstract int read() throws IOException

so it's implictly casted to be unsigned byte by storing it in an int.

As stated in documentation:

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.

Think about the fact that if it's a signed byte then -1 couldn't be used as end of stream value.

For OutputStream you have

public abstract void write(int b) throws IOException

and as stated by documentation implementation will take 8 low order bits of the integer passed..


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...