public void writeLongBits(long value, int count) throws IOException {
    if (count == 0) throw new IllegalArgumentException("Cannot write 0 bits.");

    // Make sure the value is clean of extra high bits
    value = value & (0xffffffffffffffffL >>> (64 - count));

    int remaining = count;
    while (remaining > 0) {
      int bitsToCopy = bits < remaining ? bits : remaining;

      int sourceShift = remaining - bitsToCopy;
      int targetShift = bits - bitsToCopy;

      currentByte |= (value >>> sourceShift) << targetShift;

      remaining -= bitsToCopy;
      bits -= bitsToCopy;

      value = value & (0xffffffffffffffffL >>> (64 - remaining));

      // If there are no more bits left to write to in our
      // working byte then write it out and clear it.
      if (bits == 0) {
        flush();
      }
    }
  }
 public void close() throws IOException {
   flush();
   out.close();
 }