** 這篇文章是翻譯铣猩,也是筆記,只做重點(diǎn)摘抄茴丰,詳情參考原文**
6052是什么达皿?它是在60/70年代的處理器,8bit處理器贿肩。
無符號(hào)數(shù)峦椰,carry flag的作用,比如計(jì)算下式
![Unsigned binary addition of 80 + 44 yielding 224.](https://lh4.googleusercontent.com/-AMWLf9mO9yc/UMBOXuU9mEI/AAAAAAAAPOs/ab4usXLrNDw/s400/sum1.png)
Unsigned binary addition of 80 + 44 yielding 224.
- 對(duì)于數(shù)num汰规,1的補(bǔ)碼是255-num汤功,2的補(bǔ)碼是256-num。數(shù)num + 256并不改變num的大小溜哮。所以對(duì)于減法有:
M - N = M - N + 256 = M + (256 - N) = M + N的2s補(bǔ)碼
也就是減法能用加法算了滔金。但是這里的256會(huì)影響carry flag,怎么解決茂嗓?
- 通常所說的最高為表示符號(hào)位餐茵,讓有符號(hào)加減法跟無符號(hào)一樣了。
![Signed addition of 80 and -48 yields a carry, which is discarded.](https://lh5.googleusercontent.com/-0otOTwr5udY/UMBNg575H1I/AAAAAAAAPOc/DiE5Z18puBI/s400/sum4.png)
Signed addition of 80 and -48 yields a carry, which is discarded.
80 - 48 = 80 + (256 - 48) = 256 + 32述吸,這里carry flag置位赫蛇,結(jié)果是32
- 這個(gè)時(shí)候還有一個(gè)問題就是類似80 + 80的情形
![Signed addition of 80 + 80 yields overflow.](https://lh3.googleusercontent.com/-6n2an94LcNc/UMBNTbs1FYI/AAAAAAAAPOM/2JDuAkv_Z1E/s400/sum3.png)
Signed addition of 80 + 80 yields overflow.
這個(gè)時(shí)候carry flag沒有置位充活,但是結(jié)果卻是負(fù)數(shù)框产,因?yàn)?60超出了有符號(hào)數(shù)可以表示的范圍测僵。從此引入了overflow bit
6052把overflow bit定義為有符號(hào)數(shù)的加減法計(jì)算結(jié)果不能fit into有符號(hào)數(shù)的范圍。
看一下所有溢出的可能把朴读,以M + N為例屹徘,它們都是有符號(hào)數(shù)。
![Binary addition, demonstrating the bits that affect the 6502 overflow flag.](https://lh6.googleusercontent.com/-AY1cAHDsWAU/UMBPv_AyhuI/AAAAAAAAPPM/ky7X8jRqvgQ/s400/overflow-diagram.png)
Binary addition, demonstrating the bits that affect the 6502 overflow flag.
這個(gè)表中可以看出衅金,只有M7, N7, C6對(duì)最終結(jié)果有影響噪伊,所以一共有八中可能,如下表所示
8種情況中只有兩種會(huì)有符號(hào)數(shù)操作的溢出氮唯;但是由四種情況的無符號(hào)數(shù)溢出鉴吹,但是由carry flag標(biāo)示就夠了。
計(jì)算overflow flag的公式
// common difinition惩琉,也就是說carry into C7的bit和carry out C7的bit不一致的時(shí)候發(fā)生溢出
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豆励,也就是說兩個(gè)輸入的符號(hào)和輸出的符號(hào)都不想等的時(shí)候溢出
(M^result)&(N^result)&0x80