java.math.BigInteger bitCount()
Description
A quick background on getting the 2’s complement of an integer:
Let’s say we have a decimal number of -24 then in order to get the 2’s complement of this number, write it first in binary.
16 | 8 | 4 | 2 | 1 |
1 | 1 | 0 | 0 | 0 |
then we invert it and becomes
00111
and then add 1 because of the negative notation on our integer thus the final result would be:
01000
Now let’s count how many bit’s of the two’s complement of -24, that would be 4 which we get by counting the bits of the result omitting the last digit on the left which is because it is zero.
Method Syntax
public int bitCount()
Method Argument
Data Type | Parameter | Description |
---|---|---|
N/A | N/A | N/A |
Method Returns
The bitCount() method returns an int value which corresponds to the number of bits in the two’s complement representation of this BigInteger that differ from its sign bit.
Compatibility
Requires Java 1.1 and up
Java BigInteger bitCount() Example
Below is a java code demonstrates the use of bitCount() method of BigInteger class. The example presented might be simple however it shows the behavior of the bitCount() method.
package com.javatutorialhq.java.examples; import java.math.BigInteger; import java.util.Scanner; /* * A java example source code to demonstrate * the use of bitCount() method of BigInteger class */ public class IntegerBitCountExample { public static void main(String[] args) { // get user input System.out.print("Enter the first value:"); Scanner s = new Scanner(System.in); String firstInput = s.nextLine(); s.close(); // convert the first String Input to BigInteger BigInteger val1 = new BigInteger(firstInput); /* * get the the count of bits of the * user input */ int result = val1.bitCount(); System.out.println("Bit Count of "+val1+" is "+result); } }
This example is a lot simpler than it looks. Basically we ask for user input and converted this value into BigInteger. We then printed out the results of the bitCount() operation.