为什么Java OutputStream.write()采用整数但写入字节 [英] Why Java OutputStream.write() Takes Integer but Writes Bytes

查看:1180
本文介绍了为什么Java OutputStream.write()采用整数但写入字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个OutputStream,只是在OutputStream接口注意到这一点,

I am writing an OutputStream, just noticed this in the OutputStream interface,

   public abstract void write(int b) throws IOException;

此调用向流写入一个字节,但为什么它将整数作为参数?

This call write one byte to the stream but why it takes integer as an argument?

推荐答案

实际上我最近一直在处理字节,它们可能很烦人。它们在最轻微的挑衅时向上转换为int,并且没有指定将数字转换为字节 - 例如,8l将为您提供长值8,但对于字节,您必须说(字节)8

Actually I've been working with bytes a bit lately and they can be annoying. They up-convert to ints at the slightest provocation and there is no designation to turn a number into a byte--for instance, 8l will give you a long value 8, but for byte you have to say (byte)8

除此之外,它们(几乎)将始终作为整数存储在内部,除非您使用的是数组(甚至可能......但不确定)。

On top of that, they will (pretty much) always be stored internally as ints unless you are using an array (and maybe even then.. not sure).

我认为他们只是假设使用字节的唯一原因是实际需要8位的i / o,但在内部他们希望你总是使用整数。

I think they just pretty much assume that the only reason to use a byte is i/o where you actually need 8 bits, but internally they expect you to always use ints.

顺便说一下,一个字节可以表现得更差,因为它总是必须被屏蔽......

By the way, a byte can perform worse since it always has to be masked...

至少我记得阅读那些年前,现在可能已经改变了。

At least I remember reading that years ago, could have changed by now.

作为你的具体问题的一个例子答案,如果函数(f)占用一个字节,你有两个字节(b1和b2),然后:

As an example answer for your specific question, if a function (f) took a byte, and you had two bytes (b1 and b2), then:

f(b1 & b2)

不起作用,因为b1& b2将被上转换为int,并且int无法自动下转换(精度损失)。所以你必须编码:

wouldn't work, because b1 & b2 would be up-converted to an int, and the int couldn't be down-converted automatically (loss of precision). So you would have to code:

f( (byte)(b1 & b2) )

这会让人恼火。

并且不打算问为什么b1 &安培; b2 up-convert - 我最近一直在讨论这个问题!

And don't bother asking WHY b1 & b2 up-converts--I've been cussing at that a bit lately myself!

这篇关于为什么Java OutputStream.write()采用整数但写入字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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