Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If you just want the unsigned bit sequence as an int.</p> <pre><code>static final int[] lookup = {0x0, 0x1, 0x3, 0x7, 0xF, 0x1F, 0x3F, 0x7F, 0xFF, 0x1FF, 0x3FF, 0x7FF, 0xFFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF }; /* * bytes: byte array, with the bits indexed from 0 (MSB) to (bytes.length * 8 - 1) (LSB) * offset: index of the MSB of the bit sequence. * len: length of bit sequence, must from range [0,16]. * Not checked for overflow */ static int getBitSeqAsInt(byte[] bytes, int offset, int len){ int byteIndex = offset / 8; int bitIndex = offset % 8; int val; if ((bitIndex + len) &gt; 16) { val = ((bytes[byteIndex] &lt;&lt; 16 | bytes[byteIndex + 1] &lt;&lt; 8 | bytes[byteIndex + 2]) &gt;&gt; (24 - bitIndex - len)) &amp; lookup[len]; } else if ((offset + len) &gt; 8) { val = ((bytes[byteIndex] &lt;&lt; 8 | bytes[byteIndex + 1]) &gt;&gt; (16 - bitIndex - len)) &amp; lookup[len]; } else { val = (bytes[byteIndex] &gt;&gt; (8 - offset - len)) &amp; lookup[len]; } return val; } </code></pre> <p>If you want it as a String (modification of Margus' answer).</p> <pre><code>static String getBitSequence(byte[] bytes, int offset, int len){ int byteIndex = offset / 8; int bitIndex = offset % 8; int count = 0; StringBuilder result = new StringBuilder(); outer: for(int i = byteIndex; i &lt; bytes.length; ++i) { for(int j = (1 &lt;&lt; (7 - bitIndex)); j &gt; 0; j &gt;&gt;= 1) { if(count == len) { break outer; } if((bytes[byteIndex] &amp; j) == 0) { result.append('0'); } else { result.append('1'); } ++count; } bitIndex = 0; } return result.toString(); } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload