Keeping track of leading zeros with BitSet in Java

Posted by Ryan on Stack Overflow See other posts from Stack Overflow or by Ryan
Published on 2014-06-06T16:53:25Z Indexed on 2014/06/06 21:27 UTC
Read the original article Hit count: 377

Filed under:
|

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.

© Stack Overflow or respective owner

Related posts about java

Related posts about bitset