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

查看:31
本文介绍了为什么 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?

推荐答案

实际上,我最近一直在处理字节,它们可能很烦人.他们在最轻微的挑衅下向上转换为整数,并且没有指定将数字转换为字节 - 例如,8l 会给你一个长值 8,但对于字节你必须说 (byte)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 上转换——我自己最近一直在骂这个!

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天全站免登陆