8051中的BCD到二進位制轉換
在這個問題中,我們將瞭解如何將8位BCD數轉換為其二進位制(十六進位制)等效值。BCD數儲存在20H位置。轉換後,結果將儲存在30H。
因此,假設資料為D5H。程式將D5H的二進位制值轉換為BCD值213D。
地址 | 值 |
---|---|
. . . | |
20H | 94 |
21H | |
. . . |
程式
MOVR0,#20H; Initialize the address of the data MOVA,@R0;Get the data from an address, which is stored in R0 MOVR2,A; Store the content of A into R2 CLRA;Clear the content of A to 00H MOVR3,#00H LOOP: ADDA,#01H;increment A by 01H DAA; Decimal Adjust of the accumulator content INCR3; Increase R3 to keep track of the hex value CJNEA,02H,LOOP ;Run the loop until A = R2 MOVR0,#30H; Point the destination location MOVA,R3; Move R3 to A MOV@R0,A; Store A content to the memory location pointed by R0 HALT: SJMPHALT
這裡的邏輯非常簡單。我們只是從記憶體中獲取數字。並將該值儲存到R2中。透過此值,我們可以在執行迴圈時進行比較。
累加器(A)和暫存器R3最初設定為00H。因此,我們只是將A的值增加01H。我們可以使用**INC A**指令遞增值,但在這種情況下,值是使用**ADDA, #01H**遞增的。其背後的原因是INC指令不會影響CY和AC標誌。但是,這些標誌需要使用**DA A**指令進行十進位制調整。在增加A的值後,執行DA A指令將值轉換為十進位制。透過使用此十進位制值,我們可以將其與儲存在R2中的數字進行比較。在每次迭代中,R3的值遞增1,這充當計數器。因此,最後,我們從暫存器R3獲取輸出。
輸出
地址 | 值 |
---|---|
. . . | |
20H | 94 |
21H | |
. . . | |
30H | 5E |
31H | |
. . . |
方法2
我們也可以使用其他一些邏輯來做同樣的事情。這裡不需要額外的迴圈來完成任務。我們只需將BCD數的十位數字乘以0AH。然後將第二位數字與結果相加即可得到該數。
如果數字是94,則將其乘以9的0AH。
(9 * 0AH) = 5AH, thenadding 4 with 5AH. (5AH + 4) = 5EH.
程式
MOVR0,#20H; Initialize the address of the data MOVA,@R0; Get the data from an address, which is stored in R0 MOVR2,A;Store the content of A into R2 SWAPA; Swap the nibbles of A register ANLA,#0FH;Mask the Higher Nibble of A MOVB,0AH;Take 0AH = 10D into B MULAB ;Multiply A with B, and get result into A MOVA,R2;Copy R2 content to A ANLA,#0FH;Mask the higher nibble of A ADDA,R2 MOVR0,#30H;Point the destination location MOVA,R3;Move R3 to A MOV@R0,A;Store A content to memory location pointed by R0 HALT: SJMPHALT
廣告