java - 如何在Java程序中处理Java类文件的无符号类型(尤其是u4)?

标签 java jvm bytecode unsigned

来自Java Virtual Machine specification :

A class file consists of a stream of 8-bit bytes. All 16-bit, 32-bit, and 64-bit quantities are constructed by reading in two, four, and eight consecutive 8-bit bytes, respectively. Multibyte data items are always stored in big-endian order, where the high bytes come first. In the Java platform, this format is supported by interfaces java.io.DataInput and java.io.DataOutput and classes such as java.io.DataInputStream and java.io.DataOutputStream.

This chapter defines its own set of data types representing class file data: The types u1, u2, and u4 represent an unsigned one-, two-, or four-byte quantity, respectively. In the Java platform, these types may be read by methods such as readUnsignedByte, readUnsignedShort, and readInt of the interface java.io.DataInput.

除了令人恼火地提及“64 位数量”(没有 u8long and double 分为两个 u4 项)之外,我不明白如何处理 u4 类型。

对于u1u2很清楚:

  • u1:使用readUnsignedByte读取,存储在int
  • u2:使用readUnsignedShort读取,存储在int

规范建议:

  • u4:使用readInt读取,存储在int中(?)

大于 Integer.MAX_VALUE 的值会发生什么情况?此建议是否默默暗示 u4 类型的所有值都小于或等于 Integer.MAX_VALUE

我想出了这个主意:

  • u4:使用readUnsignedInt读取,存储在long

不幸,there is no such method 。但这不是问题,因为您可以轻松编写自己的:

public long readUnsignedInt() throws IOException {
    return readInt() & 0xFFFFFFFFL;
}

所以,这里有两个有问题的地方:

  1. Code attribute :

    Code_attribute {
    ...
    u4 code_length;
    u1 code[code_length];
    ...
    }

    为什么code_length不是u2类型? Later it says :

    The value of the code_length item must be less than 65536.

  2. SourceDebugExtension attribute :

    SourceDebugExtension_attribute {
    ...
    u4 attribute_length;
    u1 debug_extension[attribute_length];
    }
    ...
    Note that the debug_extension array may denote a string longer than that which can be represented with an instance of class String.

    为什么? u4 值确实可以超过 Integer.MAX_VALUE (因为我认为这是 String 实例的最大长度)?

最佳答案

  1. 在需要时轻松解除 64K 代码长度限制。
  2. 由于没有提及 u4 值不能超过 Integer.MAX_VALUE,因此必须假设 u4 值可以超过 Integer.MAX_VALUE。 JVM 规范没有留下任何隐含的内容。

关于java - 如何在Java程序中处理Java类文件的无符号类型(尤其是u4)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11660967/

相关文章:

java - 面向程序员/开发人员的 JVM 内部规范引用

garbage-collection - java 堆中的 "live"对象是什么? (使用 jmap 进行堆转储)

python - 在 C python 中,访问字节码评估堆栈

documentation - LLVM IR 操作码文档

java - 我想从java中的excel表中删除重复的值

java - Runtime.getRuntime().exec() 不执行某些命令

java - JVM 如何在加载类时验证没有潜在的操作数堆栈溢出?

java - 热点JVM Bytecode Interpreter是跟踪JIT吗?

java - Junit 与 MockMVC - 错误 - java.lang.IllegalArgumentException : Entity must not be null

java - 使用正则表达式从字符串中提取数字