/**
* Terminate bits as described in 8.4.8 and 8.4.9 of JISX0510:2004 (p.24).
*/
private static void TerminateBits(int numDataBytes, BitVector bits)
{
var 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 (var i = 0; i < 4 && bits.Size() < capacity; ++i)
{
bits.AppendBit(0);
}
var numBitsInLastByte = bits.Size() % 8;
// If the last byte isn't 8-bit aligned, we'll add padding bits.
if (numBitsInLastByte > 0)
{
var numPaddingBits = 8 - numBitsInLastByte;
for (var 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).
var numPaddingBytes = numDataBytes - bits.SizeInBytes();
for (var 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");
}
}