1

I want to calculate the total number of bits in a BitSet object. The method length returns the "logical size" of the BitSet: the index of the highest set bit in the BitSet plus one, while method cardinality will give the total number of bits set to 1 in the object.

I want to calculate the total number of bits including both 0s and 1s. How do I do that?

seh
  • 14,999
  • 2
  • 48
  • 58
Saurabh
  • 121
  • 1
  • 2
  • 12
  • 1
    I don't think this deserves downvoting. The difference between `length` and `size` is confusing, the naming IMHO very inappropriate, and the documentation sucks. – maaartinus Sep 20 '12 at 12:50

3 Answers3

2

How about BitSet.size()?.....

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
  • size will returns the number of bits of space actually in use by this BitSet to represent bit values. – Saurabh Jun 16 '12 at 10:29
  • I want to calculate number of bits and not the space. – Saurabh Jun 16 '12 at 10:30
  • 1
    @Saurabh: I don't think `BitSet` is designed for that; there is no concept of the "highest" 0. – Oliver Charlesworth Jun 16 '12 at 10:33
  • I want to create a binary representation from bitset object, any idea how can I do that? – Saurabh Jun 16 '12 at 10:52
  • I don't understand how `BitSet#size()` does not meet your requirement. You mentioned that you're looking for both the zero- and one-valued bits. Isn't that the same as asking how many bits can be represented by the `BitSet` instance at the moment? – seh Jun 16 '12 at 13:39
  • 1
    @Saurabh there is no difference between the number of bits and the space. – user207421 Jun 16 '12 at 19:15
1

The getObjectSize(Object o) method in the Instrumentation library is your guy: http://docs.oracle.com/javase/7/docs/api/java/lang/instrument/Instrumentation.html

There are a few threads on this.

Cheers!

Community
  • 1
  • 1
-1

The site shows how to convert a BitSet to binary String. Then just calculate the string.length()

sgowd
  • 2,242
  • 22
  • 29
  • 1
    Why was this marked down? If you think it's incorrect/misleading, at least explain why. – matt freake Jun 16 '12 at 13:21
  • 2
    @Disco 3: It's like calculating the length of the String by first putting all its characters into a List and then reverting it and then calling list.size(). Totally inefficient. Moreover, the method linked is totally broken and the result would be always 32. – maaartinus Sep 20 '12 at 12:48
  • I was wrong... the method there works with `int` only, so it's not broken, just unusable for this question. And inefficient (needless reverse) and useless (see `Integer.toString(int i, int radix)`). – maaartinus Sep 20 '12 at 13:26