how to use negative numbers as one in assembly?

纵然是瞬间 提交于 2020-01-04 04:46:06

问题


I have a arithmetic program in assembly, but when i add, subtract, multiply negative numbers, it will not result in desired output.

For Example

input:

-1+2=66675 (should be 1)

-1-1=656745 (should be -2)

-1*-1=66757 (should be 1) 

Questions:

  • how would i treat (-) and (1) as one?

  • how to do arithmetic operation in signed numbers?

any advice please ...


回答1:


I recommend reading up on 2's compliment and the difference between signed and unsigned ints. The value you are showing looks suspiciously like a signed int negative value being translated into an unsigned int value without doing a conversion. Negative ints have a Most Significant Bit that is set to 1. If you shove that value into an unsigned int without first masking then you get a much larger number then expected.

Example in a 8 bit representation:

signed value = -1 
unsigned value = 255 
binary = 1111 1111

Take the twos compliment: 
       1111 1111
XOR    0000 0000
equals 0000 0000
add1   0000 0001
dec value = 1

You can learn more here (They have an example for two's compliment addition you can look at): http://academic.evergreen.edu/projects/biophysics/technotes/program/2s_comp.htm



来源:https://stackoverflow.com/questions/14817184/how-to-use-negative-numbers-as-one-in-assembly

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!