Ernusc
Ernusc

Reputation: 526

Which bit actually shift the << operator?

I confused with an operator which provides arithmetic shifts <<, >> in Java

For example I have this binary number:

   0000 0101 // It is actually 5 in dec system

And now I want to shift this number to the left by 2 positions. I am doing this ( this is only concept of shifting bits) :

 0000 0101 << 2

And now I do not know: if I need to shift high bit by 2 positions and fill with zero in right side OR I need to shift whole number (101) by 2 positions?

Upvotes: 2

Views: 121

Answers (1)

Aurelien Ribon
Aurelien Ribon

Reputation: 7634

Second option :)
For instance, 0110001 << 2 = 1000100

The other operators are:

  • signed right shift (>>).

    0011001 >> 2 = 0000110
    1011001 >> 2 = 1110110

    The leftmost bit is used as left padding. This is done to propagate the sign bit (highest bit).

  • unsigned right shift (>>>)

    1110001 >> 2 = 0011100

    Since the number is considered unsigned, there is nothing to propagate, just pad with zeros!

Upvotes: 4

Related Questions