base:two_s_complement_system

This shows you the differences between two versions of the page.

base:two_s_complement_system [2015-04-17 04:34] 127.0.0.1 external edit |
base:two_s_complement_system [2021-09-09 07:52] (current) strobe Add alternate 2's complement method, fix typo. |
||
---|---|---|---|

Line 3: | Line 3: | ||

A two' | A two' | ||

- | //The importance of this system is that it helps us represent negative numbers, while addition (ADC) and substraction (SBC) operations can be used exactly the same way as with unsigned numbers.// | + | //The importance of this system is that it helps us represent negative numbers, while addition (ADC) and subtraction (SBC) operations can be used exactly the same way as with unsigned numbers.// |

In finding the two's complement of a binary number, the bits are inverted, or " | In finding the two's complement of a binary number, the bits are inverted, or " | ||

Line 63: | Line 63: | ||

ROR A ;ROR shifts in Carry from the left, thus keeping our sign the same | ROR A ;ROR shifts in Carry from the left, thus keeping our sign the same | ||

</ | </ | ||

+ | |||

+ | ====== Alternate method ====== | ||

+ | |||

+ | An alternative to the inverse-then-increment 2's complement is to simply subtract from zero. | ||

+ | |||

+ | Unlike the above method, this also works for 16bit or larger numbers. | ||

+ | |||

+ | //This assumes your value is in memory.// | ||

+ | |||

+ | < | ||

+ | SEC | ||

+ | LDA #$00 | ||

+ | SBC Value | ||

+ | </ | ||

+ | |||

+ | 16 bit version: | ||

+ | < | ||

+ | SEC | ||

+ | LDA #$00 | ||

+ | SBC ValueLo | ||

+ | STA ValueLo | ||

+ | LDA #$00 | ||

+ | SBC ValueHi | ||

+ | STA ValueHi | ||

+ | ; Repeat the last 3 instructions as needed for any additional bytes | ||

+ | </ | ||

+ | |||

+ | Tip: If the value of the carry flag is known on entry, you can either drop the SEC if the carry is set or drop the SEC and change the initial LDA #0 to a LDA #1 if the carry is clear, saving 1 byte and 2 cycles. |

base/two_s_complement_system.txt ยท Last modified: 2021-09-09 07:52 by strobe