bitnot function

BigInt bitnot(
  1. BigInt bn, {
  2. int? bitLength,
})

Implementation

BigInt bitnot(BigInt bn, {int? bitLength}) {
  // JavaScript's bitwise not doesn't work on negative BigInts (bn = ~bn; // WRONG!)
  // so we manually implement our own two's compliment (flip bits, add one)
  bn = -bn;
  var bin = (bn).toRadixString(2).replaceAll("-", "");

  var prefix = '';
  while (bin.length % 8 != 0) {
    bin = '0' + bin;
  }

  if ('1' == bin[0] && bin.substring(1).contains('1')) {
    prefix = '1' * 8;
  }

  if (bitLength != null && bitLength > 0 && bitLength > bin.length) {
    prefix = '1' * (bitLength - bin.length);
  }

  bin = bin.split('').map((i) {
    return '0' == i ? '1' : '0';
  }).join('');

  return BigInt.parse(prefix + bin, radix: 2) + BigInt.one;
}