bitlengthInBytes static method

int bitlengthInBytes(
  1. BigInt value, {
  2. bool sign = false,
})

Minimum number of bytes needed to represent value. Pass sign: true to reserve room for the sign bit (two's-complement encoding) — required for negative values, and also affects positive values whose top bit would otherwise be misread as a sign bit.

Implementation

static int bitlengthInBytes(BigInt value, {bool sign = false}) {
  if (value.isNegative && !sign) {
    throw ArgumentException.invalidOperationArguments(
      'bitlengthInBytes',
      name: 'value',
      reason: 'Negative value requires sign: true.',
    );
  }
  int bits = value.bitLength;
  if (sign) bits += 1; // reserve the sign bit for positive and negative alike
  if (bits == 0) return 1; // value == 0
  return (bits + 7) ~/ 8;
}