terminateBits static method

void terminateBits(
  1. int numDataBytes,
  2. BitArray bits
)

Terminate bits as described in 8.4.8 and 8.4.9 of JISX0510:2004 (p.24).

Implementation

static void terminateBits(int numDataBytes, BitArray bits) {
  var capacity = numDataBytes * 8;
  if (bits.size > capacity) {
    throw WriterException(
        'data bits cannot fit in the QR Code ${bits.size} > $capacity');
  }
  for (var i = 0; i < 4 && bits.size < capacity; ++i) {
    bits.appendBit(false);
  }
  // Append termination bits. See 8.4.8 of JISX0510:2004 (p.24) for details.
  // If the last byte isn't 8-bit aligned, we'll add padding bits.
  var numBitsInLastByte = bits.size & 0x07;
  if (numBitsInLastByte > 0) {
    for (var i = numBitsInLastByte; i < 8; i++) {
      bits.appendBit(false);
    }
  }
  // If we have more space, we'll fill the space with padding patterns defined in 8.4.9 (p.24).
  var numPaddingBytes = numDataBytes - bits.sizeInBytes;
  for (var i = 0; i < numPaddingBytes; ++i) {
    bits.appendBits((i & 0x01) == 0 ? 0xEC : 0x11, 8);
  }
  if (bits.size != capacity) {
    throw WriterException('Bits size does not equal capacity');
  }
}