如何在 Go 中编写 LEB128

Ang*_*gel 5 binary go varint

你如何在 Go 中将整数写入 LEB128 格式?我正在尝试将 int32 编码为Minecraft VarInt,到目前为止我已经尝试将 wiki 上的示例导入到 Go。我在测试时得到了错误的结果,wiki 说 -1 应该等于 [255 255 255 255 15],但我得到的是 [255 255 255 255 255]。我在这里做错了什么?

func WriteVarInt2(v int32) []byte{
   var out []byte
   c := 0
   for{
       currentByte := byte(v & 0b01111111)
       v >>= 7
       if v != 0 {
           currentByte |= 0b10000000
       }
       out = append(out, currentByte)
       c++

       if c >= 5 || v == 0{
           return out
       }
    }
}
Run Code Online (Sandbox Code Playgroud)

icz*_*cza 6

问题在于移位操作。

>>算术移位右,>>>逻辑移位右。区别在于>>引入符号位(在左侧),而>>>引入零(无论符号位是什么)。

LEB128 的 Varint 的算法使用的是逻辑移位,而 Go 的>>算法是算术移位。

Go 中没有明显的逻辑转换,但是如果您将数字视为无符号数,您将得到确切的结果:

func WriteVarInt2(v_ int32) []byte {
    v := uint32(v_)

    // rest of your function unchanged
    // ...
}
Run Code Online (Sandbox Code Playgroud)

测试它:

fmt.Println(WriteVarInt2(-1))
Run Code Online (Sandbox Code Playgroud)

输出符合预期(在Go Playground上试试):

[255 255 255 255 15]
Run Code Online (Sandbox Code Playgroud)