encodeSigned static method

Uint8List encodeSigned(
  1. dynamic d
)

Can serialize an int or BigInt as a leb128 signed format.

Implementation

static Uint8List encodeSigned(dynamic d) {
    if (d is! BigInt && d is! int) {
        throw Exception('leb128 encode parameter must be an int or a BigInt');
    }

    BigInt x = d is int ? BigInt.from(d) : d;


    late String tc_bitstring;
    if (x < BigInt.from(0)) {
        int bit_size = x.abs().toRadixString(2).length + 1; // + 1 for the sign-bit
        while (bit_size % 7 != 0) { bit_size += 1; }
        tc_bitstring = bigint_as_the_twos_compliment_bitstring(x, bit_size: bit_size);
    }
    else if (x >= BigInt.from(0)) {
        tc_bitstring = '0' + x.toRadixString(2); // '0' +  for the sign-bit
    }
    while (tc_bitstring.length % 7 != 0) { tc_bitstring = '0' + tc_bitstring; }
    List<String> bytes_bitstrings = [];
    for (int i=0; i < tc_bitstring.length / 7;i++) {
        String put_high_bit = i==0 ? '0' : '1';
        bytes_bitstrings.add( put_high_bit + tc_bitstring.substring(i*7, i*7+7));
    }
    List<int> bytes = bytes_bitstrings.map((String byte_bitstring)=>int.parse(byte_bitstring, radix:2)).toList();
    return Uint8List.fromList(bytes.reversed.toList());
}