Q22Microprocessor and Microcontroller
Question
Write an assembly language program to add two 8-bit numbers with carry.
Answer
A fully functional, deeply commented 8085 assembly language program specifically engineered to add two 8-bit numbers and successfully capture any resulting 16-bit carry overflow.
When adding two 8-bit numbers, the maximum possible result () requires 9 bits to mathematically represent. Therefore, an 8-bit microprocessor will overflow and the 9th bit is captured entirely by the Carry Flag (CY). A robust program must check this flag and store the carry as a separate byte to yield a correct 16-bit result.
Memory Architecture
- Input Data 1: Memory Address
- Input Data 2: Memory Address
- Output Sum (Lower 8-bits): Memory Address
- Output Carry (Upper 8-bits): Memory Address
Assembly Code Implementation
``assembly
MVI C, 00H ; Initialize Register C to strictly 00H. This will explicitly hold our Carry.
LXI H, 2501H ; Load the H-L register pair with the memory address of the first number.
MOV A, M ; Fetch Data 1 from RAM (pointed to by HL) directly into the Accumulator.
INX H ; Increment the H-L pair to point to 2502H (location of Data 2).
ADD M ; Mathematically ADD Data 2 (from RAM) to the Accumulator.
; The sum is now in A. The Carry Flag (CY) is modified.
JNC SKIP ; (Jump if No Carry). If CY=0, skip the next instruction.
INR C ; If CY=1, increment Register C from 00H to 01H to record the carry.
SKIP: INX H ; Increment H-L to point to 2503H (destination for the Sum).
MOV M, A ; Store the final 8-bit Sum from the Accumulator directly into RAM.
INX H ; Increment H-L to point to 2504H (destination for the Carry).
MOV A, C ; Move the Carry value (00H or 01H) from Register C into Accumulator.
MOV M, A ; Store the Carry value directly into RAM.
HLT ; Halt the microprocessor execution.
``
Algorithmic Trace
Assume holds C5H and holds 92H.
1.
2. ADD M calculates .
3. The Accumulator only holds 8 bits, so it violently truncates to . The Carry Flag is SET (CY=1).
4. The JNC instruction fails (because there is a carry).
5. INR C executes, making .
6. The program stores at and stores at . The complete 16-bit result is 0157H.