title: Java convert 8 bit numbers to 10 bit
body: <p>Am reading data out of a <code>ByteBuffer</code> but the values I need are stored as 10 bits. ie:</p>
  
  <pre>11001011<b>10</b> = 814</pre>
  
  <p>I've tried using <code>BitSet</code> but this stores each byte in LSB first, which causes the final two bits to be incorrect the above example turns into:</p>
  
  <pre>11010011<b>11</b> = 815</pre>
  
  <p>an example using a sequence of numbers:</p>
  
  <pre><code>                     8 bit    10 bit
  01 02 03 04 05 06 07 08 | 09 10 | 11 12 13 14 15 16
  </code></pre>
  
  <p>would end up being:</p>
  
  <pre><code>                     8 bit    10 bit
  08 07 06 05 04 03 02 01 | 16 15 | 14 13 12 11 10 09
  </code></pre>
  
  <p>So I can manage the first byte being in either order but the final two bits are taken from the wrong end of the next byte.</p>
  
  <p>my current code is as follows:</p>
  
  <pre><code>// bb stands for the ByteBuffer in use.
  //length stands for the number bytes covering the 10 bit numbers
  BitSet data = getBitSet(bb, length);
  int totalNumbers = data.length() / 10;
  int[] numbers = new int[totalNumbers];
  for (int i=0; i &lt; totalNumbers; i++){
      int start = i*10;
      int end = (i+1)*10;
      BitSet bs = data.get(start, end);
      int tenBitNumber = 0;
      for (int j = bs.nextSetBit(0); j &gt;= 0; j = bs.nextSetBit(j+1)) {
          double power = pow(2, 9-j);
          tenBitNumber += power;
      }
      numbers[i] = tenBitNumber;
  }
  </code></pre>
  
  <p>a worked example in Big Endian format:
  sequence of bytes:</p>
  
  <pre>11001011|<b>10</b>110111|00101100|11000111</pre>
  
  <p>which transforms when using <code>BitSet</code> into:</p>
  
  <pre>11010011|<b>11</b>101101|00110100|11100011</pre>
  
  <p>What would be the best solution? I need to read multiple 10 bit length numbers from the <code>ByteBuffer</code>.</p>