gpt4 book ai didi

java - 从长度为 unsigned int 的 ByteBuffer 中读取 UTF-8 字符串

转载 作者:行者123 更新时间:2023-11-29 06:26:07 26 4
gpt4 key购买 nike

我正在尝试通过 java.nio.ByteBuffer 读取 UTF8 字符串。大小是一个 unsinged int,当然,Java 没有。我把值读成long,这样我就有了值。

我遇到的下一个问题是我无法使用 long 创建字节数组,将 long 转换回 int 将导致它被签名。

我也试过在缓冲区上使用 limit(),但它同样不能与 int 一起使用。

我正在做的具体事情是从类文件中读取 UTF8 字符串,因此缓冲区中包含的不仅仅是 UTF8 字符串。

关于如何从 ByteBuffer 中读取可能长度为 unsigned int 的 UTF8 字符串的任何想法。

编辑:

Here is an example of the issue .

SourceDebugExtension_attribute {
u2 attribute_name_index;
u4 attribute_length;
u1 debug_extension[attribute_length];
}

attribute_name_index
The value of the attribute_name_index item must be a valid index into the constant_pool table. The constant_pool entry at that index must be a CONSTANT_Utf8_info structure representing the string "SourceDebugExtension".

attribute_length
The value of the attribute_length item indicates the length of the attribute, excluding the initial six bytes. The value of the attribute_length item is thus the number of bytes in the debug_extension[] item.

debug_extension[]
The debug_extension array holds a string, which must be in UTF-8 format. There is no terminating zero byte.

The string in the debug_extension item will be interpreted as extended debugging information. The content of this string has no semantic effect on the Java Virtual Machine.

因此,从技术的角度来看,类文件中的字符串可以是完整的 u4(无符号,4 字节)长度。

如果 UTF8 字符串的大小有限制,这些就不是问题(我不是 UTF8 专家,所以可能有这样的限制)。

我可以赌一把,接受不会有那么长的字符串的现实……

最佳答案

除非您的字节数组超过 2GB(Java int 的最大正值),否则将 long 转换回一个带符号的 int

如果您的字节数组的长度需要超过 2GB,那么您做错了,尤其是因为这远远超过了 JVM 的默认最大堆大小...

关于java - 从长度为 unsigned int 的 ByteBuffer 中读取 UTF-8 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/624207/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com