title: Java. Extracting integers from bits in a byte array not fitting the byte boundary
body: <p>I have the following array of bytes:
  01010110 01110100 00100101 01001011</p>
  
  <p>These bytes are broken into two groups to encode seven integers. I know that the first group consists of 3 values 4 bits each (0101 0110 0111) that represent numbers 5,6,7. The second group consists of 4 values 5 bits each (01000 01001 01010 01011), which represent integers 8,9,10, and 11.</p>
  
  <p>To extract the integers, I am currently using the following approach. Convert the array into a binary string:</p>
  
  <pre><code>public static String byteArrayToBinaryString(byte[] byteArray)
      {
      String[] arrayOfStrings = new String[byteArray.length];
  
      for(int i=0; i&lt;byteArray.length; i++)
      {
          arrayOfStrings[i] = byteToBinaryString(byteArray[i]);
      }
  
      String bitsetString = "";
      for(String testArrayStringElement : arrayOfStrings)
      {
          bitsetString += testArrayStringElement;
      }
  
      return bitsetString;
  }
  
  // Taken from here: http://helpdesk.objects.com.au/java/converting-large-byte-array-to-binary-string
  public static String byteToBinaryString(byte byteIn) 
  {
      StringBuilder sb = new StringBuilder("00000000");
  
      for (int bit = 0; bit &lt; 8; bit++) 
      {
          if (((byteIn &gt;&gt; bit) &amp; 1) &gt; 0) 
          {
              sb.setCharAt(7 - bit, '1');
          }
      }
  
      return sb.toString();
  }
  </code></pre>
  
  <p>Then, I split the binary string into 2 substrings: 12 characters and 20 characters. Then I split each substring into new substrings, each of which has length that equals the number of bits. Then I convert each sub-substring into an integer.</p>
  
  <p>It works but a byte array representing thousands of integers takes 30 seconds to a minute to extract.</p>
  
  <p>I am a bit at a loss here. How do I do this using bitwise operators?</p>
  
  <p>Thanks a lot!</p>