Problem with BitSet.length()...



.... is that it does not return the length of the bit set. For example, if
I create a new 8-bit set:

BitSet eightBits = new BitSet(8);


Running eightBits.length() returns zero, rather than eight.

The problem is that I want to be able to convert the bit set back to an
integer at some point. I thought the easiest way would be to iterate
backwards over the bit set thus:

private static int bitsToInt(BitSet bits) {
int myInt = 0;
int binColumn = 1;

// loop over the bitset backwards, adding up the true values
for (int i=(bits.length()-1); i>=0; i--) {
myInt += (booleanToInt(bits.get(i)) * binColumn);
binColumn = (binColumn * 2);
}

return myInt;
}

But because BitSet.length only returns the length from the highest
bit that's set to "true", this doesn't work for any binary numbers that
start with zeros in the full bit set (e.g. an 8-bit set of '00111000').

I suppose my method could take in a 'length' parameter that I coul define,
but isn't there a neater way of getting the true length of a BitSet?
.



Relevant Pages

  • Re: HashMap.put error in Xcode
    ... "Any class that defines a hashCode() method ... an int would be suitable as a key in a HashMap. ... The Key to a hashmap is an actual key, not the hash of the key. ... BitSet being on or off. ...
    (comp.lang.java.programmer)
  • Re: unsigned long long and bitset quirk
    ... > a quirk (bug?) about unsigned long long support and the bitset. ... > unsigned long long int f; ... That's because bitset doesn't have a constructor ...
    (comp.lang.cpp)
  • Re: HashMap.put error in Xcode
    ... a BitSet will not have a unique hash code. ... There can only be 2^32 hash codes, but there are many more possibilities for BitSet. ... other than construction we don't need to know you are using HashMap. ... you are trying to use an int where an Object is expected. ...
    (comp.lang.java.programmer)
  • Re: metapost or something? Coordinate system - transformation with cosine...
    ... I think my bitset works... ... See this example (stolen from google groups): ... int main ... I suggest adding `using namespace std;', ...
    (comp.text.tex)