6502 Shorts - Toggle carry. By Lee Davison
[Back]
Carry bit the wronge sense? Want a 0 when it's 1? Read on....The code.
Recently in some otherwise elegant code the result of a compare left the carry bit in exactly the wrong sense for the following add. The usual way to fix that is to do something like ..
BCC WasClear ; if clear go set it CLC ; was set so clear it BCC AllDone ; continue WasClear SEC ; was clear so set it AllDoneWhile this works there had to be a more elegant way of doing this. It turns out there is, you do this ..
ROL A ; Cb into D0 EOR #$01 ; toggle bit ROR A ; D0 into CbThe ROL puts the carry into bit 0 in the accumulator.
The EOR toggles the state of that bit without affecting any other bits.
The ROR puts the bit back into the carry, restores the accumulator and sets the N and Z flags.There are a couple of advantages of doing things this way instead of the branch and set (or clear) given earlier ..
There is one possible disadvantage in that it sets the N and Z flags from what is in A at the time. But, most of the time, if you're interested in the carry state the N and Z states are unimportant.It only takes four bytes instead of six. It always takes six cycles, not five or seven depending on the state of the carry.