writePadding method

int writePadding()

Writes padding bits to ensure proper byte alignment and returns the length of the written padding.

Since data is flushed in blocks of 8 bits (bytes), if the internal buffer's size is not a multiple of 8, padding bits are needed to ensure that the remaining bits are properly flushed.

The padding format consists of a 1 bit (the head) followed by an optional sequence of 0 bits until a full byte is completed.


  • If the internal unflushed buffer contains 5 bits (e.g., 00110) and you call writePadding, it will add a 1 bit and 2 0 bits (100) to the buffer, completing the byte to flush (00110100). This ensures that the unflushed bits can be written to bytesBuffer and later be read, with knowledge of how to remove the padding.

  • If there are no unflushed bits, a full padding byte (10000000) is written to bytesBuffer.

See isAtPadding.


int writePadding() {
  if (_bitsBufferLength == 0) {
    var padding = (1 << 7);
    return 8;
  } else {
    final gapBits = 8 - _bitsBufferLength;
    assert(gapBits > 0);

    var padding = 1 << (gapBits - 1);

    return writeBits(padding, gapBits);