【问题标题】:Negative number causes VarInt's encoding function to crash负数导致 VarInt 的编码函数崩溃
【发布时间】:2020-05-17 11:04:15
【问题描述】:

我尝试在 Python 中实现下面的函数,但是一旦我输入负数,函数就会崩溃。有人知道为什么吗?

public static void writeVarInt(int value) {
    do {
        byte temp = (byte)(value & 0b01111111);

        value >>>= 7;
        if (value != 0) {
            temp |= 0b10000000;
        }
        writeByte(temp);
    } while (value != 0);
}

这是我的功能:

def write_varint(array, data):
    first_pass = True
    while data != 0 or first_pass:
        first_pass = False
        temp = (data & 0b01111111)
        data >>= 7

        if data != 0:
            temp |= 0b10000000

        print(temp)

        write_byte(array, temp)

def write_byte(array, data):
    write_bytes(array, struct.pack('>b', data))

def write_bytes(array, source_bytes):
    for byte in source_bytes:
        array.append(byte)

【问题讨论】:

    标签: python network-protocols varint


    【解决方案1】:
    if data != 0: 
        temp |= 0b10000000
    

    data 的值为-1 时,此条件不会被调用,因此temp 最终超出了所需[-128, 127] 的范围,并在调用struct.pack() 函数时崩溃(这需要该范围内的数字)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-07
      • 2013-07-04
      相关资源
      最近更新 更多