Showing posts with label bits. Show all posts
Showing posts with label bits. Show all posts

Monday, April 25, 2011

Java: count the number of one bits in an int

Integer.bitCount counts the number of one-bits in the two's complement binary representation of the specified int value. Example code:
public class CountOnes {
    public static void main(String[] args) {
 int[] i = { 1, 4, 7, 15 };
 for (int j = 0; j < i.length; j++) {
     System.out.printf("Number of 1's in %d: %d\n", i[j], Integer.bitCount(i[j]));
 }
    }
}

Thursday, April 21, 2011

Storing integral types in java


All the integer types in Java technology are internally stored in two's complement. In two's complement, positive numbers have their corresponding binary representation.
For negative numbers see - 2's complement of negative numbers in java

Monday, April 18, 2011

How to find whether a number is a power of 2 or not in Java?

There can be many possible solutions to this problem, but probably the most efficient remains to be the one which uses bit-level manipulation wisely.

We'll talk about only that solution here and since it involves bit-level manipulation of binary sequences, so should you require a refresh, first go through this article - 2's complement of negative number.

As is the case with many other solutions which use bits intelligently, this one is also very compact. That's the beauty of bit-handling. Let's first see what the solution is and then try to understand it. It becomes very easy to understand once you get the binary sequence representations right.

Java method to check if the passed parameter is a power of 2 or not

public boolean checkIfItsPowerOf2(int n){

 if( (n & -n) == n){
  
  //passed parameter is a power of 2
  return true;
 }
 else{
  //not a power of 2
  return false;
 }
}

Verify this method. :)

Binary representation of negative numbers in java : 2's complement

Negative numbers in Java are represented using 2's complement. As we know that integers in Java occupy 4 bytes so to understand how a negative integer (say -4) is represented internally in Java, we first need to find the binary equivalent of the positive value of the integer (in this case 4) and subsequently by finding the 2's complement of that binary representation.

Okay, so how do find 2's complement of a binary number? Simply by adding '1' to the 1's complement of that number. But, how to find 1's complement of a binary number then? Just by reverting the bits of the number i.e., changing 1s to 0s and 0s to 1s. An example may of of some help here.

Example
int i = -4;
...

Step #1: Binary Equivalent of the positive value (4 in this case)

0000 0000 0000 0000 0000 0000 0000 0100

Step #2: 1's complement of the binary rep of 4 by inverting the bits

1111 1111 1111 1111 1111 1111 1111 1011

Step #3: Finding 2's complement by adding 1 to the corresponding 1's complement

1111 1111 1111 1111 1111 1111 1111 1011
0000 0000 0000 0000 0000 0000 0000 0001
---------------------------------------
1111 1111 1111 1111 1111 1111 1111 1100

Thus, we see that integer -4 is represented by the binary sequence (1111 1111 1111 1111 1111 1111 1111 1100) in Java.

Once we have an understanding of how the numbers are represented internally, bit-level manipulation becomes easily understandable, which otherwise is obviously one of the hardest things in Java (or any other language supporting that) to visualize.

Monday, August 2, 2010

Converting an integer to binary string - Binary.java


/*************************************************************************
 *  Compilation:  javac Binary.java
 *  Execution:    java Binary n
 *  
 *  Prints out n in binary.
 * 
 *  % java Binary 5
 *  101
 *
 *  % java Binary 106
 *  1101010
 *
 *  % java Binary 0
 *  0
 * 
 *  % java Binary 16
 *  10000
 *
 *  Limitations
 *  -----------
 *  Does not handle negative integers.
 *
 *  Remarks
 *  -------
 *  could use Integer.toBinaryString(N) instead.
 *
 *************************************************************************/

public class Binary { 
    public static void main(String[] args) { 

        // read in the command-line argument
        int n = Integer.parseInt(args[0]);

        // set v to the largest power of two that is <= n
        int v = 1;
        while (v <= n/2) {
            v = v * 2;
        }
  
        // check for presence of powers of 2 in n, from largest to smallest
        while (v > 0) {

            // v is not present in n 
            if (n < v) {
                System.out.print(0);
            }

            // v is present in n, so remove v from n
            else {
                System.out.print(1);
                n = n - v;
            }

            // next smallest power of 2
            v = v / 2;
        }

        System.out.println();

    }

}

Though written a program, we can use inbuilt lib of java - See here.

Chitika