Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

java - Why does ByteArrayOutputStream use int?

Maybe someone can help me understand because I feel I'm missing something that will likely have an effect on how my program runs.

I'm using a ByteArrayOutputStream. Unless I've missed something huge, the point of this class is to create a byte[] array for some other use.

However, the "plain" write function on BAOS takes an int not a byte (ByteArrayOutputStream.write).

According to this(Primitive Data Types) page, in Java, an int is a 32-bit data type and a byte is an 8-bit data type.

If I write this code...

int i = 32;
byte b = i;

I get a warning about possible lossy conversions requiring a change to this...

int i = 32;
byte b = (byte)i;

I'm really confused about write(int)...

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

In order to facilitate unsigned bytes above 0x7F this takes place. The int will be silently narrowed to be written. In fact, the code does that with a (byte) cast.

As Ingo states:

A possible reason could be that the byte to write will most often be the result of some operation that automatically converts its operands to int[, like] some bit operations. Hence, the code would be littered with casts to byte, that add nothing to understanding.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...