replaceBitRange method

int replaceBitRange(
  1. int left,
  2. int right,
  3. int bits
)

Returns an int replacing the bits from left to right with bits.

Implementation

int replaceBitRange(int left, int right, int bits) {
  final size = left - right;
  // Elongate bits so that "1b" becoms "1000b", for example, where L = 4.
  var result = bits;
  var stretch = left - result.bitLength;
  if (bits.isSet(size)) {
    stretch++;
  }
  result = result << math.max(0, stretch);
  // Create a mask of 1s for the bits to be replaced.
  final mask = (~(~0 << (size + 1))) << right;
  return (this & ~mask) | (result & mask);
}