/// <summary> Terminate bits as described in 8.4.8 and 8.4.9 of JISX0510:2004 (p.24).</summary> internal static void terminateBits(int numDataBytes, BitVector bits) { int capacity = numDataBytes << 3; if (bits.size() > capacity) { throw new WriterException("data bits cannot fit in the QR Code" + bits.size() + " > " + capacity); } // Append termination bits. See 8.4.8 of JISX0510:2004 (p.24) for details. // TODO: srowen says we can remove this for loop, since the 4 terminator bits are optional if // the last byte has less than 4 bits left. So it amounts to padding the last byte with zeroes // either way. for (int i = 0; i < 4 && bits.size() < capacity; ++i) { bits.appendBit(0); } int numBitsInLastByte = bits.size() % 8; // If the last byte isn't 8-bit aligned, we'll add padding bits. if (numBitsInLastByte > 0) { int numPaddingBits = 8 - numBitsInLastByte; for (int i = 0; i < numPaddingBits; ++i) { bits.appendBit(0); } } // Should be 8-bit aligned here. if (bits.size() % 8 != 0) { throw new WriterException("Number of bits is not a multiple of 8"); } // If we have more space, we'll fill the space with padding patterns defined in 8.4.9 (p.24). int numPaddingBytes = numDataBytes - bits.sizeInBytes(); for (int i = 0; i < numPaddingBytes; ++i) { if (i % 2 == 0) { bits.appendBits(0xec, 8); } else { bits.appendBits(0x11, 8); } } if (bits.size() != capacity) { throw new WriterException("Bits size does not equal capacity"); } }