OP here. I found the answer to my question.
Shifting left may trigger arithmetic overflow.
The range of numbers expressible by a two's complement system is from -(2^(n-1))
to 2^(n-1)-1
, where n
is the number of bits available, including the sign bit (MSB). So, in the above example where each number uses 4 bits, the range of possible values is -8
to 7
, inclusive.
Shifting left by m
bits will multiply the number by 2^m
. So, in the above example -5 << 1
would yield -10
, which is beyond the range of possible numbers in a 4-bit signed representation – that's an overflow.
1111 << 1 == 1110 // -1 * 2 is -2
1110 << 1 == 1100 // -2 * 2 is -4
1101 << 1 == 1010 // -3 * 2 is -6
1100 << 1 == 1000 // -4 * 2 is -8
1011 << 1 == 0110 // overflow
1010 << 1 == 0100 // overflow
1001 << 1 == 0010 // overflow
1000 << 1 == 0000 // overflow
In conclusion, while using ASL to multiply by powers of two, it is important to make sure the product lies within the range of possible values.
<<
meet the requirements of both ASL and LSL. Does an ASL operation somehow preserve the most significant bit (sign bit)? If so, does it do it by shifting out bits, starting with the second bit instead of the MSB? – sgarza6210110
. – sgarza62