bigint_as_the_twos_compliment_bitstring function

String bigint_as_the_twos_compliment_bitstring(
  1. BigInt x, {
  2. required int bit_size,
})

Implementation

String bigint_as_the_twos_compliment_bitstring(BigInt x, {required int bit_size}) { // bit_size can technically be BigInt or Int
    final BigInt max_size = BigInt.from(2).pow(bit_size-1)-BigInt.from(1);
    final BigInt min_size = -BigInt.from(2).pow(bit_size-1);
    if (x > max_size || x < min_size) {
        throw Exception('value must be >= ${min_size} and value <= ${max_size} for a ${bit_size} bit integers. ');
    }
    String bitstring = '';
    if (x >= BigInt.from(0)) {
        bitstring = x.toRadixString(2);
        while (bitstring.length < bit_size) { bitstring = '0' + bitstring; }
    }
    else if (x < BigInt.from(0)) {
        bitstring = '1';
        String bitstring_part2  =  (min_size.abs() - x.abs()).toRadixString(2);
        while (bitstring_part2.length < bit_size-1) { bitstring_part2 = '0' + bitstring_part2; }
        bitstring += bitstring_part2;
    }
    if (bitstring.length < bit_size) {
        throw Exception('something happen');
    }
    return bitstring;
}