Hoda Osama Hoda Osama - 4 years ago 102
Java Question

Loop array of bytes only for ones

I have an array of bytes. Some are 0's and some are 1's.

import java.util.Arrays;

byte[] bytes = new byte[100];


I want to loop only for 1's. How to do this?

Answer Source

i don't want to loop on all array because it has large size . i

Actually 100 bytes is trivial. It uses 2 cache lines. However if you wanted to improve performance you would use a bit set which only use one bit per 0 or 1 instead of 8.

BitSet bs = new BitSet(1 << 20); // 1 Mb
for(int i = 0; (i = bs.nextSetBit(i+1)) >= 0;)
    System.out.println("Next set bit is " + i);

This still has to loop through the data but it can examine 64-bits at once.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download