由于java语言规则或jvm,是否将字节转换为int? [英] Is addition of byte converts to int because of java language rules or because of jvm?

查看:171
本文介绍了由于java语言规则或jvm,是否将字节转换为int?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

byte a = 1;
byte b = 1;
byte c = a + b;

引发错误:可能会失去精确度

Throws error: possible loss of precision

byte subt = a_s - a_b;
                ^
  required: byte
  found:    int

这是行为与jvm或它在java语言中定义有关。

Is this behavior has something to do with jvm or its been defined in java language .

编辑:如果它是用java语言定义那么就做因为记住jvm?

EDIT : And if it is defined in java language then does it because of keeping jvm in mind ?

意味着如果java支持 byte datatype那么为什么操作on byte results int

Means if java supports byte datatype then why operation on byte results int

推荐答案


如果java支持byte数据类型,那么为什么对byte进行操作会导致int

if java supports byte datatype then why operation on byte results int

因为这就是Java虚拟机的设计方式。没有指令集对字节类型执行操作。相反, int 类型的指令集用于 boolean byte char 类型。

Because that's how the Java Virtual Machine is designed. There is no instruction set to perform operation on a byte type. Rather the instruction set for int type is used for the operation on boolean, byte, char, and short types.

来自 JVM规范 - 第2.11.1节


编译器对类型 byte 的文字值加载进行编码, short 使用Java虚拟机指令在编译时将这些值签名扩展为 int 类型的值 - 时间。类型 boolean char 的文字值的加载使用将文字零扩展为类型值的指令进行编码 int 在编译时或运行时。 [..]。因此,对实际类型的值的大多数操作 boolean byte char short 由运行于计算类型 int 的值的指令正确执行。

A compiler encodes loads of literal values of types byte and short using Java Virtual Machine instructions that sign-extend those values to values of type int at compile-time or run-time. Loads of literal values of types boolean and char are encoded using instructions that zero-extend the literal to a value of type int at compile-time or run-time. [..]. Thus, most operations on values of actual types boolean, byte, char, and short are correctly performed by instructions operating on values of computational type int.

背后的原因也在该部分中指明:

The reason behind this is also specified in that section:


鉴于Java虚拟机的单字节操作码大小,将编码类型编码到操作码中会对其指令集的设计造成压力。如果每个类型化指令都支持所有Java虚拟机的运行时数据类型,则会有比在字节中表示的更多指令。 [...]可以根据需要使用单独的指令在不支持和支持的数据类型之间进行转换。

Given the Java Virtual Machine's one-byte opcode size, encoding types into opcodes places pressure on the design of its instruction set. If each typed instruction supported all of the Java Virtual Machine's run-time data types, there would be more instructions than could be represented in a byte. [...] Separate instructions can be used to convert between unsupported and supported data types as necessary.

有关所有内容的详细信息指令集可用于各种类型,您可以查看该部分中的表。

For the details on what all instruction sets are available for various types, you can go through the table in that section.

还有一个表指定实际类型到JVM计算类型的映射:

There is also a table specifying the mapping of actual type to the JVM computational type:

这篇关于由于java语言规则或jvm,是否将字节转换为int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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