title: Optimize function to write bits to file
body: <p>Here is a function that writes n bits to a binary file. </p>
  
  <p>Parameters:</p>
  
  <ul>
  <li>Data : Bit sequence to be written to file (lsb on the right)</li>
  <li>Length: Number of bits to write</li>
  <li>OutFile: Destination file.</li>
  </ul>
  
  <p>First version of the funcion:</p>
  
  <pre><code>void WriteBitsToFile(unsigned long long Data, unsigned Length, std::ofstream &amp; OutFile) {
      static unsigned long long BitBuffer = 0;
      static unsigned BitCounter = 0;
  
      for (unsigned i = Length; i --; ) {
          (BitBuffer &lt;&lt;= 1) |= ((Data &gt;&gt; i) &amp; 0x1);
          BitCounter ++;
  
          if (BitCounter == 64) {
              OutFile.write((char *) &amp; BitBuffer, sizeof(BitBuffer));
              BitCounter = 0;
          }
      }
  }
  </code></pre>
  
  <p>Second version:</p>
  
  <pre><code>void WriteBitsToFile(unsigned long long Data, unsigned Length, std::ofstream &amp; OutFile) {
      static unsigned long long BitBuffer = 0;
      static unsigned FreeBitCounter = sizeof(BitBuffer) &lt;&lt; 3;
  
      Data &amp;= (1 &lt;&lt; Length) - 1;
  
      if (FreeBitCounter &gt; Length) {
          BitBuffer |= (Data &lt;&lt; (FreeBitCounter -= Length));
      } else if (FreeBitCounter &lt; Length) {
          BitBuffer |= (Data &gt;&gt; (Length -= FreeBitCounter));
          OutFile.write((char *) &amp; BitBuffer, sizeof(BitBuffer));
          BitBuffer = Data &lt;&lt; ((sizeof(BitBuffer) &lt;&lt; 3) - Length);
          FreeBitCounter = (sizeof(BitBuffer) &lt;&lt; 3) - Length;
      } else {
          BitBuffer |= Data;
          OutFile.write((char *) &amp; BitBuffer, sizeof(BitBuffer));
          BitBuffer = 0; FreeBitCounter = (sizeof(BitBuffer) &lt;&lt; 3);
      }
  }
  </code></pre>
  
  <p>Both of them do the job, but second one is faster then first. Any idea to make it even faster?</p>
  
  <p>Thank you all for help!</p>