A guarantee of a negative result when offsetting a left negative number by two's complement?
Assuming that a negative binary number represented in two additions , we can guarantee the preservation of the sign?
Let's say we represent a decimal number -5
in four bits: 1011
and we want to left shift one place to multiply by 2:
1011 << 1
This operation returns 0110, which is 6, not -10 as we hoped .
(I assume this only applies to negative numbers whose second bit is 0, i.e. negative numbers close to the smallest representable negative number of some range)
source to share
OP is here. I found the answer to my question.
Left shift can cause arithmetic overflow .
The range of two's complement numbers is from -(2^(n-1))
to 2^(n-1)-1
, where n
is the number of bits , including the sign bit (MSB). So, in the example above, where each number uses 4 bits, the range of possible values is from -8
to, 7
inclusive.
Shifting left by a bit m
will multiply the number by 2^m
. So the example above -5 << 1
gives -10
, which is out of the range of possible numbers in a 4-bit signed representation, is 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, when using ASL to multiply by powers of two, it is important to ensure that the product is within the range of possible values.
source to share