bit manipulation - Why does a right shift on a signed integer causes an overflow? -
given 8 bits negative integer (signed between -1 , -128), right shift in hla causes overflow , don't understand why. if shifted once, should divide value 2. true positive numbers not negative. why? example if -10 entered result +123.
program cpy; #include ("stdlib.hhf") #include ("hla.hhf") static i:int8; begin cpy; stdout.put("enter value divide 2: "); stdin.geti8(); mov(al,i); shr(1,i); //shift bits 1 position right if(@o)then // if overlow stdout.put("overflow"); endif; end cpy;
signed numbers represented 2's complement in binary, plus sign bit "on left". 2's complement of 10 coded on 7 bits 1110110, , sign bit value negative numbers 1.
-10: 1111 0110 ^ | sign bit
then shift right (when right shift zeroes added left):
-10 >> 1: 0111 1001 ^ | sign bit
your sign bit worth 0 (positive), , 1111011 123 in decimal.
Comments
Post a Comment