0

I try to implement the function below in Python but as soon as I enter a negative number the function crashes. Does anyone understand why?

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

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

Here my function :

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)

Tao
  • 11
  • 3

1 Answers1

0
if data != 0: 
    temp |= 0b10000000

When data value is -1 this conditional does not get called and therefore temp ends up out of range of the needed [-128, 127], and wounds up crashing when struct.pack() function gets called (which requires a number within that range).

felipe
  • 7,324
  • 2
  • 28
  • 37