Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><s>Just wondering why can't you use <code>java.util.BitSet;</code> </s></p> <p>Basically what you can do, is to read the whole data as <code>byte[]</code>, convert it to binary in <code>string</code> format and use string utilities like <code>.substring()</code> to do the work. This will also work <code>bit sequences &gt; 16</code>. </p> <p>Lets say you have 3 bytes: <code>1, 2, 3</code> and you want to extract bit sequence from 5th to 16th bit.</p> <p><strong>Number Binary</strong></p> <pre><code>1 00000001 2 00000010 3 00000011 </code></pre> <p><strong>Code example:</strong></p> <pre><code>public static String getRealBinary(byte[] input){ StringBuilder sb = new StringBuilder(); for (byte c : input) { for (int n = 128; n &gt; 0; n &gt;&gt;= 1){ if ((c &amp; n) == 0) sb.append('0'); else sb.append('1'); } } return sb.toString(); } public static void main(String[] args) { byte bytes[] = new byte[]{1,2,3}; String sbytes = getRealBinary(bytes); System.out.println(sbytes); System.out.println(sbytes.substring(5,16)); } </code></pre> <p><strong>Output:</strong></p> <pre><code>000000010000001000000011 00100000010 </code></pre> <p><strong>Speed:</strong></p> <p>I did a testrun for <strong>1m</strong> times and on my computer it took <strong>0.995s</strong>, so its reasonably very fast:</p> <p>Code to repeat the test yourself:</p> <pre><code>public static void main(String[] args) { Random r = new Random(); byte bytes[] = new byte[4]; long start, time, total=0; for (int i = 0; i &lt; 1000000; i++) { r.nextBytes(bytes); start = System.currentTimeMillis(); getRealBinary(bytes).substring(5,16); time = System.currentTimeMillis() - start; total+=time; } System.out.println("It took " +total + "ms"); } </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