Sunday, September 29, 2013

Printing the number in binary format

How do we write a program to print the binary representation of an integer?

For the sake of simplicity, let us assume that the integer takes 32 bits. The integer 367 is represented in binary as follows.

0000 0000 0000 0000 0000 0001 0110 1111

Iterative Method:

In this method we extract the bit at each of the 32 positions from left to right. The bit at ith position can be found by performing bit-wise & operation between the following numbers
2i & num

In the following  Java Program, 2i is calculated by 1<<i. This is efficient way of calculating 2 raised to the power of i. This method prints all the leading 0s also.

public static void printBinary(int num)
        int i = 31;
        while( i >= 0)
            int mask = 1 << i;
            int bit = (num & mask) == 0 ? 0: 1;

Recursive Method:

In this function as long as num > 0, we recursively call the function by halving the number. When the number reaches 0, the stack unwinding happens. We print the remainder of num when divided by 2 (num%2). This method trims all the leading 0s if present but this works for only for non-negative integers.

public static void printBinaryRecursive(int num)
        if( num > 0)
            printBinaryRecursive( num/2 );
            System.out.print( num%2 );