gpt4 book ai didi

java - int 的可变长度编码为 2 个字节

转载 作者:行者123 更新时间:2023-11-30 06:08:21 24 4
gpt4 key购买 nike

我正在实现可变长度编码和读取wikipedia关于它。这是我发现的:

0x00000080  0x81 0x00

这意味着0x80 int被编码为0x81 0x00 2个字节。这是我无法理解的。好的,按照那里列出的算法,我们就有了。

  1. 二进制0x80:00000000 00000000 00000000 10000000
  2. 我们将符号位移动到下一个八位字节,因此我们将 和 设置为 1(表明我们有更多的八位字节):00000000 00000000 00000001 10000000 不等于 0x81 0x00。我尝试为此编写一个程序:

    byte[] ba = new byte[]{(byte) 0x81, (byte) 0x00};
    int first = (ba[0] & 0xFF) & 0x7F;
    int second = ((ba[1] & 0xFF) & 0x7F) << 7;
    int result = first | second;
    System.out.println(result); //prints 1, not 0x80

ideone

我错过了什么?

最佳答案

让我们回顾一下维基百科页面上的算法:

  1. 采用整数的二进制表示
  2. 将其分成 7 位组,具有最高值的组将具有较少的值
  3. 将这七个位作为一个字节,将除最后一个之外的所有位的 MSB(最高有效位)设置为 1;最后一个保留为 0

我们可以这样实现算法:

public static byte[] variableLengthInteger(int input) {
// first find out how many bytes we need to represent the integer
int numBytes = ((32 - Integer.numberOfLeadingZeros(input)) + 6) / 7;
// if the integer is 0, we still need 1 byte
numBytes = numBytes > 0 ? numBytes : 1;
byte[] output = new byte[numBytes];
// for each byte of output ...
for(int i = 0; i < numBytes; i++) {
// ... take the least significant 7 bits of input and set the MSB to 1 ...
output[i] = (byte) ((input & 0b1111111) | 0b10000000);
// ... shift the input right by 7 places, discarding the 7 bits we just used
input >>= 7;
}
// finally reset the MSB on the last byte
output[0] &= 0b01111111;
return output;
}

您可以看到它适用于维基百科页面 here 中的示例。 ,您也可以插入自己的值并在线尝试。

关于java - int 的可变长度编码为 2 个字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50799164/

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