Skip to main content

8085 ALP: count ones in upper nibble

Short answer

Isolate upper nibble with ANI F0H. Rotate left four times to test each bit in carry flag, counting ones in a register. Store the total count of ones in the upper nibbles of ten numbers at the location just after the table (e.g., 200AH).

Write a program in 8085 to calculate the number of ones in the upper nibble of ten 8-bit numbers stored in a table. Store the count of ones in a location just after the table.

Assumptions: the table is at 2000H-2009H. The question is read as the total number of 1s in the upper nibbles of all ten numbers, stored at 200AH (the location just after the table).

Method: the upper nibble is isolated with ANI F0H. Then A is rotated left four times, and each time the bit that goes into CY is tested; the count register E is incremented when it is 1.

        LXI H,2000H     ; HL -> table
        MVI C,0AH       ; 10 numbers
        MVI E,00H       ; E = total count of ones
LOOP:   MOV A,M
        ANI 0F0H        ; keep upper nibble only
        MVI B,04H       ; four bits (D7..D4) to test
BITLP:  RLC             ; move next bit into CY
        JNC SKIP
        INR E           ; bit is 1 -> count it
SKIP:   DCR B
        JNZ BITLP
        INX H
        DCR C
        JNZ LOOP
        MOV M,E         ; HL now points just after the table (200AH)
        HLT

Example: table values A5H and 0FH give upper nibbles A (two ones) and 0 (none), so 2 is added to the count. (If a separate count for each number is wanted, store E in a result table after each number and clear E at the start of each number.)

✓ Answer checked by Claude Opus 5.5 (high effort)

All Microprocessor chapter 2 questions →