Skip to main content

8085 ALP: interchange two bits of bytes

Short answer

The bits are swapped only if D1 and D4 differ. The byte is rotated left 3 times to align D1 with D4; XOR with original gives D1 xor D4 at D4. Mask 10H, shift back to D2 (02H), OR with 10H to form toggle mask 12H if different or 00H if same; XOR with original to swap. 20 bytes transferred.

Write an ALP in 8085 to transfer 20 bytes of data in a table to another table by interchanging D1 and D4 bits of each byte.

Assumptions: source table at 2000H (20 bytes), destination table at 2100H. Bit numbering D7 ... D0.

Method: D1 and D4 are exchanged only when they differ; in that case both bits are toggled. The byte is rotated left 3 times so that D1 lines up with D4; XOR with the original byte gives (D1 xor D4) in position D4; masking and shifting back builds the toggle mask 12H (or 00H); XOR with the original byte completes the swap.

        LXI H,2000H     ; HL -> source table (20 bytes)
        MVI D,14H       ; counter = 20 decimal
LOOP:   MOV A,M         ; A = byte
        MOV B,A         ; keep a copy of original byte in B
        RLC             ; rotate left 3 times: original D1 comes to D4
        RLC
        RLC
        XRA B           ; bit D4 of A = (D1 xor D4) of original
        ANI 10H         ; keep only D4: 10H if D1 and D4 differ, else 00H
        MOV C,A         ; C = 10H or 00H
        RRC             ; move the difference flag to D1 (10H -> 02H)
        RRC
        RRC
        ORA C           ; A = 12H if bits differ, 00H if same
        XRA B           ; toggle D1 and D4 only when they differ = swap
        INR H           ; destination is source + 0100H (2100H)
        MOV M,A         ; store swapped byte in table 2
        DCR H           ; back to source table
        INX H           ; next byte
        DCR D           ; one byte done
        JNZ LOOP        ; repeat for all 20 bytes
        HLT

Check: byte 10H (D4 = 1, D1 = 0) gives a mask of 12H, so 10H xor 12H = 02H, which is the exchanged result. A byte like 12H (both 1) gives mask 00H and stays 12H.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Microprocessor chapter 2 questions →