1

why 3 right shift 32 is equal to 3 and not 0.

I got these results in nodeJs and Java

  • 3 >> 31 = 0
  • 3 >> 32 = 3
  • 3 >> 33 = 1
  • 3 >> 34 = 0
  • 3 >> 35 = 0
Stack Danny
  • 7,754
  • 2
  • 26
  • 55
Aniket Prajapati
  • 373
  • 3
  • 19
  • 6
    C++ is not NodeJs and Java. – user202729 May 29 '19 at 08:42
  • 4
    That's undefined behavior. – L. F. May 29 '19 at 08:42
  • There is no runtime check of shift value and shifting with a value larger than 32 depends on the processor behavior. So for the language, it is undefined behavior. Most probably, there is only 5 bits in the instruction field to specify the shift and only the 5 LSB of shift value are kept. So >>32 is equivalent to >>0, >>33 is equivalent to >>1 and so on. – Alain Merigot May 29 '19 at 08:47
  • Same for shift to left n<<32 === n – Yaroslav Gaponov May 29 '19 at 08:49
  • It looks like some cyclic shift: length of int32 is 32. So for shif greater than or equals to 32 something like this is happens: val >> (shift % 32). For 32 it will be 0 and 3 >> 0 = 3, for 33 the shift will be 33 % 32 = 1 -> 3 >> 1 = 1. – alexey28 May 29 '19 at 08:52

1 Answers1

7

This is part of the Java language specification. The right hand operand is wrapped so that it is always in the range 0 - bits, where bits is the number of bits of the left hand operand. Since you are shifting a 32 bit integer, the right hand operand is wrapped within 0 to 31. 32 becomes 0, 33 becomes 1 etc.

See the Java language specification for shift operators:

If the promoted type of the left-hand operand is int, only the five lowest-order bits of the right-hand operand are used as the shift distance. It is as if the right-hand operand were subjected to a bitwise logical AND operator & (§15.22.1) with the mask value 0x1f (0b11111). The shift distance actually used is therefore always in the range 0 to 31, inclusive.

Max Vollmer
  • 8,412
  • 9
  • 28
  • 43