Yes, just test each bit in turn using a mask. For integers there are 32 possible bits.
Luckily java provides this for you:
Integer.bitCount(value)
If you wanted to do it yourself:
int value = Integer.parseInt("1000101010", 2);
int bitCounter = 0;
for (int i = 0; i < Integer.SIZE; i++) {
if (((1 << i) & value) > 0) {
bitCounter++;
}
}
System.out.println(value + " has " + bitCounter + " bits");
Output
554 has 4 bits
If alternatively you wanted the "length", i.e. the number of 0s or 1s...
Convert to string and find length
System.out.println(Integer.toString(value, 2).length());
Use some knowledge of maths to take the base(2) log of the value.
double valueUnsigned;
if (value < 0) {
valueUnsigned = (value & 0x7FFFFFF) + 0x80000000l;
} else {
valueUnsigned = value;
}
System.out.println("Maths solution " + Math.floor(1d + Math.log(valueUnsigned) / Math.log(2)));
inthas size 4 bytes = 32 bits. Bam, there you go! As a more serious answer, if you have them stored as integers already, you can use a loop and bit-shifting, keeping track of the last1you find, because what you're actually looking for is the minimum number of bits to represent that number, right?Integer.toBinaryString(int i)