Binary Left Shift Operator

 The binary left shift (<<) operator shifts the bits of the left operand to the left by the number of positions specified by the right operand. This effectively multiplies the number by 

2bitsToBeShifted2^{\text{bitsToBeShifted}}.

Exception: Overflow and Bitwise Behavior

In languages like Java, C, and C++, primitive integral types have a fixed bit-width (e.g., int is 32 bits in Java and C++ on most systems). When left-shifting a number, if the result exceeds the maximum value (MAX_VALUE) of its type, overflow occurs. However, there are some nuances:

1. Overflow in Signed Integer Types

  • Signed integers use two's complement representation.
  • If shifting causes the most significant bit (MSB) to move into the sign bit position, the number may become negative.
  • Further shifts can lead to an unpredictable sequence of positive and negative values.

Example in Java (int is 32-bit, signed):

int x = 1 << 31;  // 0b10000000000000000000000000000000 = -2147483648 (Integer.MIN_VALUE)
int y = 1 << 32;  // Shifting 32 times is equivalent to shifting 0 times (remains 1)
  • 1 << 31 results in Integer.MIN_VALUE (-2147483648).
  • 1 << 32 has no effect because only the lower 5 bits of the shift count are considered (32 mod 32 = 0), so the result is 1.

2. Shifting Negative Numbers

If a negative number is left-shifted, it behaves the same way as a positive number in terms of bit shifting but can quickly overflow into positive and negative values.

Example:

int neg = -2;          // 11111111111111111111111111111110 (in 32-bit binary)
int result = neg << 1; // 11111111111111111111111111111100 (-4 in decimal)
  • Here, shifting does not cause a sign flip, but if more bits are shifted out, the behavior might be unpredictable.

3. Unsigned Shift Alternative in Java (>>>)

Java provides an unsigned right shift (>>>), but there is no unsigned left shift. In contrast, C and C++ support unsigned integers, which do not store negative values.

Example in Java (>>> used for unsigned shift)

int x = -1;        // 0xFFFFFFFF (all bits set)
int y = x >>> 1;   // 0x7FFFFFFF (removes sign bit, becomes positive)

Key Takeaways

  1. Overflow causes signed integers to become negative due to two's complement representation.
  2. Negative numbers follow the same shifting rules but may lead to unpredictable values.
  3. In Java, shifts beyond the bit-width (32 for int) wrap around using modulo (% 32).
  4. Unsigned types in C/C++ prevent negative numbers, but Java lacks an unsigned left shift (<<).


Comments

Popular posts from this blog