This program counts the number of 0 bits and 1 bits in a given 8-bit number.

Description

The program uses bit rotation and the carry flag to examine each bit of a number and count how many 0s and 1s it contains.

Registers Used

  • AL: Input byte
  • CL: Bit counter (8 bits)
  • BL: Count of 1s
  • BH: Count of 0s

Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
MOV AL, 0F3H       ; Example number: 11110011b
MOV CL, 08H        ; Bit counter = 8 bits
MOV BL, 00H        ; Count of 1's
MOV BH, 00H        ; Count of 0's

NEXT_BIT:
    ROL AL, 1       ; Rotate left through carry
    JC ONE          ; If carry = 1 ? bit was 1
    INC BH          ; Otherwise, increment 0's counter
    JMP SKIP

ONE:
    INC BL          ; Increment 1's counter

SKIP:
    DEC CL
    JNZ NEXT_BIT    ; Repeat for all 8 bits

HLT                 ; Stop execution

Explanation

Algorithm

  1. Initialization

    • Load the test number (0F3H = 11110011b) into AL
    • Set bit counter CL = 8
    • Initialize counters: BL (1s) = 0, BH (0s) = 0
  2. Bit Examination Loop

    • ROL AL, 1: Rotate AL left, MSB goes to carry flag
    • JC ONE: If carry = 1, the bit was 1
    • INC BH: If carry = 0, increment 0s counter
    • JMP SKIP: Skip the 1s counter increment
  3. ONE Label

    • INC BL: Increment 1s counter
  4. Loop Control

    • DEC CL: Decrement bit counter
    • JNZ NEXT_BIT: Continue if more bits to check

Example Result

For input 0F3H (11110011b):

  • BL = 6 (six 1-bits)
  • BH = 2 (two 0-bits)

Binary Breakdown

Bit:    7  6  5  4  3  2  1  0
Value:  1  1  1  1  0  0  1  1
        ^  ^  ^  ^        ^  ^
        1s ------        1s --
                  0s ----

Key Instructions

  • ROL: Rotate left (moves MSB to carry)
  • JC: Jump if carry flag is set
  • INC: Increment register
  • JNZ: Jump if not zero (CL ≠ 0)