Tuesday, June 10, 2014

Privacy Policy

If you require any more information or have any questions about our privacy policy, please feel free to contact us by email at ashvinbhide@gmail.com.

At www.binary-imaginers.blogspot.com, the privacy of our visitors is of extreme importance to us. This privacy policy document outlines the types of personal information is received and collected by www.binary-imaginers.blogspot.com and how it is used.

Log Files
Like many other Web sites, www.binary-imaginers.blogspot.com makes use of log files. The information inside the log files includes internet protocol ( IP ) addresses, type of browser, Internet Service Provider ( ISP ), date/time stamp, referring/exit pages, and number of clicks to analyze trends, administer the site, track user’s movement around the site, and gather demographic information. IP addresses, and other such information are not linked to any information that is personally identifiable.

Cookies and Web Beacons
www.binary-imaginers.blogspot.com does not use cookies.

DoubleClick DART Cookie
.:: Google, as a third party vendor, uses cookies to serve ads on www.binary-imaginers.blogspot.com.
.:: Google's use of the DART cookie enables it to serve ads to users based on their visit to www.binary-imaginers.blogspot.com and other sites on the Internet.
.:: Users may opt out of the use of the DART cookie by visiting the Google ad and content network privacy policy at the following URL - http://www.google.com/privacy_ads.html

Some of our advertising partners may use cookies and web beacons on our site. Our advertising partners include ....
Google Adsense


These third-party ad servers or ad networks use technology to the advertisements and links that appear on www.binary-imaginers.blogspot.com send directly to your browsers. They automatically receive your IP address when this occurs. Other technologies ( such as cookies, JavaScript, or Web Beacons ) may also be used by the third-party ad networks to measure the effectiveness of their advertisements and / or to personalize the advertising content that you see.

www.binary-imaginers.blogspot.com has no access to or control over these cookies that are used by third-party advertisers.

You should consult the respective privacy policies of these third-party ad servers for more detailed information on their practices as well as for instructions about how to opt-out of certain practices. www.binary-imaginers.blogspot.com's privacy policy does not apply to, and we cannot control the activities of, such other advertisers or web sites.

If you wish to disable cookies, you may do so through your individual browser options. More detailed information about cookie management with specific web browsers can be found at the browsers' respective websites.

Monday, June 2, 2014

java program to count minimum number of bits required to convert a given number into another number


Question: Write a Java program that will return the number of bits that will need to be changed in order to convert an integer, X, into another integer, Y and vice versa.

Explanation: The method should accept two different integers as input. For example, if your method is passed the integers 12 and 16 then your method should return a 3 . 

Let's take a closer look at the example given to us. It says that for the input of a 12 and 16, the output of the method should be a 3. Since we are looking for the number of bits that will need to be changed, let's convert 12 and 16 to binary to further understand this bit manipulation problem. The binary representation of 12 is 01100 and the binary representation of 16 is 10000. Comparing the binary representation of those two numbers, we can see that the first 3 digits are different, which means that to convert 12 to 16 or 16 to 12 we would have to change 3 numbers. And that is why the method that we write should output a 3.

Solution:The binary operator that is perfect for this exercise is the XOR operator. If you need a refresher on how that operator works you can read this: XOR in Java. This is because the XOR operator will return true when the binary digits being compared are different, but will return false when they are the same. So, if we just XOR the two numbers being passed in, the result of the XOR operation will be binary number that will have a binary 1 each and every time there is a different bit between the inputs x and y, and a binary 0 when the bits in the input x and y are the same. So, for example, if we XOR 1001 and 0101 the result of the XOR operation would be a 1100 because the 2 leftmost bits are different, so the result of XOR'ing those 2 bits would be a 1 but the 2 rightmost bits in our inputs are the same, so the result of XOR would be a 0. 

So, the algorithm to solve this bit manipulation interview question would be:

First, XOR the two numbers being passed in - call them x and y - and then call the result Z.
Then, just count the number of binary 1′s in Z since that count represents the number of different bits in the two numbers x and y. In order to count the number of binary 1′s in Z, we can just take Z, and perform the binary AND operation with the number 1. When the result of that operation is a 1 then we know that the very last binary digit in Z is a 1. Then, we can shift Z by 1 bit and repeat until there is nothing left to shift - which is when Z is equal to 0. 

Here is the Java implementation of that algorithm and our final answer to this problem:  

Bit-wise and bit shift operations:

public class BitDiffernce {
    public  int findNumberOfBits(int x, int y) {
        int bitCount = 0;
        int z = x ^ y;  //XOR x and y

        while (z != 0) {
            //increment count if last binary digit is a 1:

            bitCount += z & 1;       
            z = z >> 1;  //shift Z by 1 bit to the right
        }
        return bitCount;
    }

    public static void main(String args[]) {
        BitDiffernce bd = new BitDiffernce();
        System.out.println("No of bits needed to change are: "+
                   bd.findNumberOfBits(12, 46));        
    }
} 


You will get following output:


Output:                                                      
====================================================== 
  
No of bits needed to change are:2



Bitwise and Bit Shift Operators in Java

This post is all about basic understanding of operators that perform bit-wise and bit shift operations on integral types that Java programming language provides.


The bitwise operators:

OperatorNameExampleResultDescription
a & band3 & 511 if both bits are 1.
a | bor 3 | 5 71 if either bit is 1.
a ^ bxor 3 ^ 5 61 if both bits are different.
~anot ~3 -4Inverts the bits.
n << pleft shift3 <<< 212Shifts the bits of n left p positions. Zero bits are shifted into the low-order positions.
n >> pright shift5 >> 21Shifts the bits of n right p positions. If n is a 2's complement signed number, the sign bit is shifted into the high-order positions.
n >>> pright shift-4 >>> 28 15Shifts the bits of n right p positions. Zeros are shifted into the high-order positions.

Note:  "<<<" is not an operator, because it would be redundant. Lets see each operator one by one:

The unary bitwise complement operator:

 

The unary bitwise complement operator "~" inverts a bit pattern; it can be applied to any of the integral types, making every "0" a "1" and every "1" a "0".
 For example: A byte contains 8 bits; applying this operator to a value whose bit pattern is "00000000" would change its pattern to "11111111"

The bitwise & operator:

 

Bitwise AND operator works similar to logical AND operator (&&) and returns 1 if both operands are 1. Difference with bitwise AND and logical AND also known as short-circuit AND operator is that, logical AND operator applies only to boolean type. Also bitwise AND operator is denoted by singe & while short circuit AND operator is denoted by &&. 
For example:If A represent 0010 and B represent 1010 then result of A&B would be 0010.

The bitwise ^ operator:


Bitwise XOR operator is denoted by ^ and also work on individual bits. There is no short-circuit XOR operator in Java and result of bitwise XOR operator is XOR operation of individual bits. see the truth table of XOR operation for predicting result. in short bitwise XOR operators will return 1 if both bits are different and return 0 if both bits are same.

The bitwise | operator:


Bitwise OR operator is also similar to bitwise AND operator and applies to individual bits. It’s different than short-circuit OR operator, which is denoted by (||) and operates on boolean variable. Bitwise OR operator produce result of OR operation on two bits. Like other bitwise operator in Java, bitwise OR is only applicable to integral types.

Left shift (<<)


Integers are stored, in memory, as a series of bits. For example, the number 6 stored as a 32-bit int would be:
00000000 00000000 00000000 00000110
Shifting this bit pattern to the left one position (6 << 1) would result in the number 12:
00000000 00000000 00000000 00001100 
As you can see, the digits have shifted to the left by one position, and the last digit on the right is filled with a zero.

 Note: Shifting left is equivalent to multiplication by powers of 2. So 6 << 1 is equivalent to 6 * 2, and 6 << 3 is equivalent to 6 * 8. A good optimizing compiler will substitute shifts for multiplications when possible.

Non-circular shifting :

 

Please note that these are not circular shifts. Shifting this value to the left by one position (3,758,096,384 << 1):
11100000 00000000 00000000 00000000
results in 3,221,225,472:
11000000 00000000 00000000 00000000
The digit that gets shifted "off the end" is lost. It does not wrap around

Logical right shift (>>>) 


A logical right shift is the converse to the left shift. Rather than moving bits to the left, they simply move to the right. For example, shifting the number 12:
00000000 00000000 00000000 00001100
to the right by one position (12 >>> 1) will get back our original 6:
00000000 00000000 00000000 00000110
So we see that shifting to the right is equivalent to division by powers of 2.

Lost bits are gone

 

However, a shift cannot reclaim "lost" bits. For example, if we shift this pattern:
00111000 00000000 00000000 00000110
to the left 4 positions (939,524,102 << 4), we get 2,147,483,744:
10000000 00000000 00000000 01100000 
and then shifting back ((939,524,102 << 4) >>> 4) we get 134,217,734:
00001000 00000000 00000000 00000110
We cannot get back our original value once we have lost bits.

Arithmetic right shift (>>)

 

The arithmetic right shift is exactly like the logical right shift, except instead of padding with zero, it pads with the most significant bit. This is because the most significant bit is the sign bit, or the bit that distinguishes positive and negative numbers. By padding with the most significant bit, the arithmetic right shift is sign-preserving.

For example, if we interpret this bit pattern as a negative number:
10000000 00000000 00000000 01100000
we have the number -2,147,483,552. Shifting this to the right 4 positions with the arithmetic shift (-2,147,483,552 >> 4) would give us:
11111000 00000000 00000000 00000110
or the number -134,217,722.

So we see that we have preserved the sign of our negative numbers by using the arithmetic right shift, rather than the logical right shift. And once again, we see that we are performing division by powers of 2.

Here a simple java program showing Bit-wise and bit shift operations:


public class tetBitOperator{
 
public static void main(String args[]) {
      int a = 60; /* 60 = 0011 1100 */  
      int b = 13; /* 13 = 0000 1101 */
      int c = 0;

      System.out.println("a="+a);
      System.out.println("b="+b);
      
      c = a & b;       /* 12 = 0000 1100 */ 
      System.out.println("a & b = " + c );

      c = a | b;       /* 61 = 0011 1101 */
      System.out.println("a | b = " + c );

      c = a ^ b;       /* 49 = 0011 0001 */
      System.out.println("a ^ b = " + c );

      c = ~a;          /*-61 = 1100 0011 */
      System.out.println("~a = " + c );

      c = a << 2;     /* 240 = 1111 0000 */
      System.out.println("a << 2 = " + c );

      c = a >> 2;     /* 215 = 1111 */
      System.out.println("a >> 2  = " + c );

      c = a >>> 2;     /* 215 = 0000 1111 */
      System.out.println("a >>> 2 = " + c )
 }
}
 
Output
==========================================================================
a & b = 12
a | b = 61
a ^ b = 49
~a = -61
a << 2 = 240
a >> 2  = 15
a >>> 2 = 15