0

The signed subtraction with borrowing is rather confusing in x86 assembly. Consider the following words

X = 3A12 H
Y = 4023 H

I wrote the following code

   data1   dw 3a12h
   data2   dw 4023h
   data3   dw ?
   ;------- THEN --------
   mov al, byte ptr data1
   mov bl, byte ptr data2
   sub al, bl                ; 12-23 = EF while carry=1
   mov byte ptr data3, al
   mov al, byte ptr data1+1
   mov bl, byte ptr data2+1
   sbb al, bl                ; 3A-1(carry from sub)-40=F9 while carry=1
   mov byte ptr data3+1, al 

Now what is stored in the data3 is F9EF while the Carry flag is 1. We as humans now that result is negative. In other words, the result is actually -0611 H. But the computer doesn't know that...

Next, in other instructions it will treat F9EF as a positive number. Isn't that correct? How x86 know that F9EF is a negative number?

You may say that the sign bit is 1. OK... Then if I want to use F9EF as a positive number (or unsigned), how should I tell him?!

mahmood
  • 23,197
  • 49
  • 147
  • 242
  • 6
    x86 assembly does not care about how you interpret the data, especially the signness. It just runs the instructions. You have to use the appropriate ones for what you need to do with the data. – Laurent H. Oct 21 '16 at 18:09
  • Can you explain with an example? So, it's the programmers duty to care that. But how? – mahmood Oct 21 '16 at 18:35
  • Well for example you can use instructions to perform the two's complement to retrieve 0611H from F9EFH – Laurent H. Oct 21 '16 at 18:40
  • Is that `NEG` instruction? – mahmood Oct 21 '16 at 18:44
  • Well, you know if I enter two numbers in the program, then I know the result and will put necessary instructions to handle the result if it is negative. But assume, the program receives two number from the user. Then when should I perform two's complement and when should I ignore that? – mahmood Oct 21 '16 at 18:46
  • 2
    You as the programmer (or some other person who wrote the requirements for the program) decide the valid range of inputs for your program. If you decide that you will accept signed 8-bit values (-128..127) and the user enters 200, you should be able to detect that the value is out of range while converting from string to integer. Then you can take the appropriate action (e.g. displaying an error message to the user). – Michael Oct 21 '16 at 19:02
  • Do you know what two's complement is? – fuz Oct 21 '16 at 19:55
  • 1
    Read **[Understanding Carry vs. Overflow conditions/flags](http://teaching.idallen.com/dat2343/10f/notes/040_overflow.txt)** for signed vs. unsigned. (linked from the [x86 tag wiki](http://stackoverflow.com/tags/x86/info)). – Peter Cordes Oct 21 '16 at 20:28
  • another duplicate: http://stackoverflow.com/questions/40276790/how-does-assembly-code-know-if-a-value-is-signed-or-unsigned – Peter Cordes Oct 27 '16 at 10:31

0 Answers0