Wednesday, March 28, 2018

The Carry Flag


With Easter coming up this weekend, I have posted my Easter Egg Generator on Spelchan.com. The instructions for the processor were implemented in groups related to how the function worked with the order partially dictated on requirements, so instructions that were essential for writing code with other instructions were implemented first. The order I cover the instructions over the next few months (there is a lot to cover) are the actual order the instructions were implemented into my emulator. All the instructions are covered in detail so this can also be considered a crash course on 6502 assembly language for those not already familiar with it.

The carry flag is used in mathematical operations which indicate that the last add operation has carried a bit to the next byte. It is also used in subtraction to indicate that the last operation has borrowed from the higher byte. Some shift operations will also use this to This allows you to chain together multiple bytes to have numbers that are larger than a single byte. I will have an article explaining multi-byte numbers once we get to the point where we are implementing the instructions that are used for that.



Some instructions will work slightly differently based on whether the carry flag is set or not. For ADC you want to clear the carry flag before proceeding, while SBC must set the carry flag before use and uses carry to indicate that a borrow is required (an underflow if carry is clear).

The state of the carry flag can be controlled using the SEC and CLC instructions which we will implement now. These, as well as the rest of the flag setting and getting instructions, are very simple to implement. Setting a flag is simply using the logical or operation to set the appropriate bit. Clearing is a bit more complicated as you create an inverse of the byte that has all bits set except the desired bit and then use logical and to turn only that bit off leaving the other bits in the flag register alone. Inverting bits can be done by using 0xFF and exclusive or to toggle the flag bit off.

CLCClear Carry Flag
Address Mode
Decimal OPCode
Hexadecimal OpCode
Size
Cycles
Implied
24
$18
1
2
Flags affected: C
Usage: This sets the carry flag. It is used before using ADC or ASL, LSR when shifting in a zero
Test Code:
     SEC
     CLC
     BRK
Implementation:
m->run {
     m.state.flags = m.state.flags and (255 xor CARRY_FLAG)
}


SECSet Carry Flag
Address Mode
Decimal OPCode
Hexadecimal OpCode
Size
Cycles
Implied
56
$38
1
2
Flags affected: C
Usage: Before subtraction or shifting when you want the carry flag set (1)
Test Code:
     CLC
     SEC
     BRK
Implementation:
m->run {
                m.state.flags = m.state.flags or CARRY_FLAG
}

No comments:

Post a Comment