Mouna
Mouna

Reputation: 3359

What does the binary operator << mean?

In java there are >>, << and >>> operators.

According to Java doc

The signed left shift operator "<<" shifts a bit pattern to the left, and the signed right shift operator ">>" shifts a bit pattern to the right. The bit pattern is given by the left-hand operand, and the number of positions to shift by the right-hand operand. The unsigned right shift operator ">>>" shifts a zero into the leftmost position, while the leftmost position after ">>" depends on sign extension.

I am newbie with binary data and I found this explanation a bit ambiguous, there is no example or a use case. Could someone give me an example or a use case for these operators?

Thanks,

Upvotes: 0

Views: 145

Answers (3)

myself
myself

Reputation: 11

We have the following numbers in decimal and binary:

8 = 0000 1000

15 = 0000 1111

10 = 0000 1010

Then we use the << operator and we have the following results:

8 << 1 --> 0001 0000 = 16

15 << 2 --> 0011 1100 = 60

10 << 1 --> 0001 0100 = 20

As you can see, the operator shifts the binary representation of a number by the number of digits given by the right operand. Doing so, you obtain a new number.

Upvotes: 1

kirti
kirti

Reputation: 4609

    public class Test {

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

         c = a << 2;     /* 240 = 1111 0000 */
         System.out.println("a << 2 = " + c );
    //this will shift the binary version of a to two bits left side and insert zero in remaining places
         c = a >> 2;     /* 215 = 1111 */
         System.out.println("a >> 2  = " + c );
    //this will shift the binary version of a to left by two bits right  insert zero in remaining places
         c = a >>> 2;     /* 215 = 0000 1111 */
         System.out.println("a >>> 2 = " + c );
//this will shift the binary of a to 3bits right  insert zero in remaining places
      }
    } 

Upvotes: 2

Sumit Singh
Sumit Singh

Reputation: 15886

Java Doc

The signed left shift operator "<<" shifts a bit pattern to the left, and the signed right shift operator ">>" shifts a bit pattern to the right. The bit pattern is given by the left-hand operand, and the number of positions to shift by the right-hand operand. The unsigned right shift operator ">>>" shifts a zero into the leftmost position, while the leftmost position after ">>" depends on sign extension.

Upvotes: 4

Related Questions