On this page
Count 0s and 1s in a Byte
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
| |
Explanation
Algorithm
Initialization
- Load the test number (0F3H = 11110011b) into AL
- Set bit counter CL = 8
- Initialize counters: BL (1s) = 0, BH (0s) = 0
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
ONE Label
- INC BL: Increment 1s counter
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)