Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keeping track of leading zeros with BitSet in Java

Tags:

java

bitset

So, according to this question there are two ways to look at the size of a BitSet.

  1. size(), which is legacy and not really useful. I agree with this. The size is 64 after doing:

    BitSet b = new BitSet(8);

  2. length(), which returns the index of the highest set bit. In the above example, length() will return 0. This is somewhat useful, but doesn't accurately reflect the number of bits the BitSet is supposed to be representing in the event you have leading zeros.

The information I'm dealing with rarely(if ever) falls evenly into 8-bit bytes, and the leading 0s are just as important to me as the 1s. I have some data fields that are 333 bits long, some that are 20, etc.

Is there a better way to deal with bit-level details in Java that will keep track of leading zeros? Otherwise, I'm going to have to 'roll my own', so to speak. To which I have a few ideas already, but I'd prefer not to reinvent the wheel if possible.

like image 674
Shaz Avatar asked Oct 31 '22 22:10

Shaz


1 Answers

I had a same issue and I didn't find a built-in solution ,But make some changes is not so expensive.

public class MyBitSet extends BitSet {

    int realSize;


    public MyBitSet(int realsize) {
        // TODO Auto-generated constructor stub

        super(realsize);
        this.realSize=realsize;
    }

    public int realSize()
    {
        return this.realSize;
    }
}
like image 131
CoderInNetwork Avatar answered Nov 12 '22 17:11

CoderInNetwork