bipush在JVM中如何工作? [英] How does bipush work in JVM?
问题描述
我知道iload接受的是-1到5的整数,但是如何使用bipush指令扩展到更高的数字?特定的整数如何与字节码一起存储?
I understand iload takes in integers -1 to 5, but how can you extend to higher numbers using a bipush instruction? How is the specific integer being stored with the bytecode?
推荐答案
有几种不同的指令可用于推送整数常量.
There's several different instructions that can be used to push an integer constant.
最小的是iconst_ *指令.这些只是一个字节,因为该值是在操作码本身中编码的. iconst_1,iconstt_2等是不同的操作码.例如,iconst_5
将被编码为字节08
.
The smallest is the iconst_* instructions. These are only a single byte, because the value is encoded in the opcode itself. iconst_1, iconst_2, etc. are different opcodes. iconst_5
for example would be encoded as the byte 08
.
注意:iload
是完全不相关的指令,用于加载局部变量的值.您一定已经在考虑使用icont _ *.
Note: iload
is a completely unrelated instruction used for loading the value of a local variable. You must have been thinking of iconst_*.
下一个是bipush
,它可以在-128到127之间推送一个常数.此指令的长度为两个字节-第一个字节为操作码,第二个字节为带符号的8位整数.您甚至可以使用它在-1到5范围内推送常量,尽管这样做会在类文件中占用不必要的更多空间.例如,bipush 5
将被编码为10 05
. (0x10是bipush的操作码)
Next is bipush
, which can push a constant between -128 and 127. This instruction is two bytes long - the first byte is the opcode, and the second byte is a signed 8 bit integer. You can even use it to push constants in the range -1 to 5, although doing so would take up more space in the classfile than necessary. For example, bipush 5
would be encoded as 10 05
. (0x10 is the opcode for bipush)
下一个是sipush
,除了它存储一个16位常量而不是8位常量之外,其他均相同,因此该指令的长度为3个字节. sipush的操作码为0x11,因此sipush 5
将被编码为三个字节的序列11 00 05
.
Next is sipush
, which is the same except that it stores a 16 bit constant instead of an 8 bit constant, and hence the instruction is three bytes long. The opcode for sipush is 0x11, so sipush 5
would be encoded as the three byte sequence 11 00 05
.
您可能想知道如何存储不适合16位的整数常量.在这种情况下,编译器在类文件的称为常量池的单独部分中创建条目,然后使用ldc
或ldc_w
指令引用常量池条目.
You might wonder how integer constants which don't fit in 16 bits are stored. In this case, the compiler creates entries in a separate section of the classfile called the constant pool, and then uses the ldc
or ldc_w
instruction to refer to the constant pool entry.
这篇关于bipush在JVM中如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!