Shifting and Rotating bits ========================== The 6502's rotate instructions rotate nine bits through the carry flag. You can rotate eight bits with the following instructions: \ RLC A - 8-bit rotate left circular, leaves Carry=old bit 7 :\ Cy A=abcdefgh CMP #&80 :\ a abcdefgh ROL A :\ a bcdefgha \ RLC A - 8-bit rotate left circular, leaves Carry clear :\ Cy A=abcdefgh ASL A :\ a abcdefg0 ADC #0 :\ 0 bcdefgha \ RRC A - 8-bit rotate right circular, leaves Carry=old bit 0 :\ Cy A=abcdefgh PHA :\ ? abcdefgh ROR A :\ h ?abcdefg PLA :\ h abcdefgh ROR A :\ h habcdefg The 6502's shift instructions are logical shifts with a zero bit entering the data to replace bits moved out. You can do an arthimetic shift with the following instructions: \ ASR A - Arithmetic shift right - new bit 7 is the same as old bit 7 :\ Cy A=abcdefgh CMP #&80 :\ a abcdefgh ROR A :\ h aabcdefg The following rotates two bits through an 8-bit left circular rotate: \ Rotate two bits left through A :\ Cy A=abcdefgh ASL A :\ a bcdefgh0 ADC #&80 :\ b Bcdefgha ROL A :\ B cdefghab This gives an efficient way to swap the two nybbles in the A register: \ SWP A - swap nybbles :\ Cy A=abcdefgh ASL A :\ a bcdefgh0 ADC #&80 :\ b Bcdefgha ROL A :\ B cdefghab ASL A :\ c defghab0 ADC #&80 :\ d Defghabc ROL A :\ D efghabcd Setting, Clearing and Copying bits of data ========================================== AND xx will clear the bits in A that are also clear in xx, for example: A xx after AND xx %abcdefgh %01010101 %0b0d0f0h ORA xx will set the bits in A that are also set in xx, for example: A xx after ORA xx %abcdefgh %01010101 %a1c1e1g1 EOR xx will toggle the bits in A that are set in xx, for example: A xx after EOR xx %abcdefgh %01010101 %aBcDeFgH To clear the bits in A that are ''set'' in xx, use both ORA and EOR, for example: A xx after ORA xx after EOR xx %abcdefgh %01010101 %a1c1e1g1 %a0c0e0g0 You can copy a number of bits to a memory location without changing the other bits using EOR and AND. For example, to copy the top four bits of A into a memory location without changing the bottom four bits, use the following: A=12345678 dst=abcdefgh EOR dst ******** abcdefgh AND #&F0 ****0000 abcdefgh EOR dst 1234efgh abcdefgh STA dst 1234efgh 1234efgh This is much more efficient than the usual code: PHA LDA dst:AND #&0F:STA dst PLA AND #&F0:ORA dst:STA dst Swapping data ============= You can swap the contents of two memory locations by EORing them with each other: \ SWP addr1,addr2 - swap contents of addr1 and addr2 LDA addr1 EOR addr2:STA addr1 EOR addr2:STA addr2 EOR addr1:STA addr1 This is in contrast to the usual way of using a temporary variable: \ Swapping two bytes of data with a temporary memory location LDA addr1:STA tmp LDA addr2:STA addr1 LDA tmp:STA addr2 \ Swapping two bytes of data with a temporary register LDX addr1 LDA addr2:STA addr1 STX addr2