0

why is it that in assembly language that if I subtract a variables value from a register that has a value of zero that I end up getting the two’s complement of that variable’s value?

If I have an var1 with the value ‘D’ and then subtract it from a bh register that has a value of 0. I get the twos complement however logic tells me that with hexadecimal i subtract 15 and then add 1 . If i translated it to binary I would flip the bits and add 1. So how does MASM come to conclusion without these formulas?

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
L Mac
  • 9
  • 2
  • Where are you getting 15 from? I'm not sure I follow your formulas. However, if you're asking why you don't have to do the two's complement yourself, it's because the hardware does it for you. See https://en.wikipedia.org/wiki/Arithmetic_logic_unit – General Grievance Mar 23 '22 at 01:47
  • A hexadecimal digit ranges from 0-15 in which A-F is 10-15. Per my instructor to get a twos complement Subtract 15 from the number and add 1. – L Mac Mar 23 '22 at 01:58
  • 3
    You misunderstood your instructor. Something like that would work for 4 bits but `bh` is 8 bits. The result of subtracting `0xD` from zero in `bh` would be `0xF3`. As for your general formula of "flip the bits and add 1" that can be worked out as `-x = 0 - x = 2^n - x = (2^n - 1 - x) + 1 = ~x + 1` (for n bits). – Jester Mar 23 '22 at 02:05
  • 1
    `-x` is the definition of the complement of x, and x86 is a 2's complement machine so `0-x = -x` is the 2's complement of whatever number you started with, same as if you used the `neg` instruction, or inefficiently used some bitwise operations to do it in multiple steps using an identity like `-x = ~x + 1`. https://en.wikipedia.org/wiki/Two%27s_complement / [How to prove that the C statement -x, ~x+1, and ~(x-1) yield the same results?](https://stackoverflow.com/q/2278518) / [Explain why x == ~(~x + 1) + 1 (two's complement and back!)](https://stackoverflow.com/q/33566989) – Peter Cordes Mar 23 '22 at 02:19

0 Answers0