[译]The 6502 overflow flag explained mathematically

** 这篇文章是翻译,也是笔记,只做重点摘抄,详情参考原文**

  • 6052是什么?它是在60/70年代的处理器,8bit处理器。

  • 无符号数,carry flag的作用,比如计算下式

Unsigned binary addition of 80 + 44 yielding 224.
  • 对于数num,1的补码是255-num,2的补码是256-num。数num + 256并不改变num的大小。所以对于减法有:
M - N = M - N + 256 = M + (256 - N) = M + N的2s补码

也就是减法能用加法算了。但是这里的256会影响carry flag,怎么解决?

  • 通常所说的最高为表示符号位,让有符号加减法跟无符号一样了。
Signed addition of 80 and -48 yields a carry, which is discarded.

80 - 48 = 80 + (256 - 48) = 256 + 32,这里carry flag置位,结果是32

  • 这个时候还有一个问题就是类似80 + 80的情形
Signed addition of 80 + 80 yields overflow.

这个时候carry flag没有置位,但是结果却是负数,因为160超出了有符号数可以表示的范围。从此引入了overflow bit

  • 6052把overflow bit定义为有符号数的加减法计算结果不能fit into有符号数的范围。

  • 看一下所有溢出的可能把,以M + N为例,它们都是有符号数。

Binary addition, demonstrating the bits that affect the 6502 overflow flag.
  • 这个表中可以看出,只有M7, N7, C6对最终结果有影响,所以一共有八中可能,如下表所示

  • 8种情况中只有两种会有符号数操作的溢出;但是由四种情况的无符号数溢出,但是由carry flag标示就够了。

  • 计算overflow flag的公式

// common difinition,也就是说carry into C7的bit和carry out C7的bit不一致的时候发生溢出
OV = C6 XOR C7

// M7 and N7 are both 0 and C6 is 1 or
// M7 and N7 are both 1 and C6 is 0
V = (!M7&!N7&C6) | (M7&N7&!C6)

// hardware implemation
V = not (((m7 nor n7) and c6) nor ((M7 nand N7) nor c6))

// high level language,也就是说两个输入的符号和输出的符号都不想等的时候溢出
(M^result)&(N^result)&0x80

你可能感兴趣的:([译]The 6502 overflow flag explained mathematically)