Count the Number of 1s in a Register
Write a program in Assembly Language to Count the Number of 1’s in a Register . Program should load number in register and then should implement some logic for counting Number of 1’s in a Register .
How our Logic Works for this Problem
- We have a word that is stored in AX register.
- Initialize the counter 1 = 16.
- Initialize counter 2 = 0 to count the number of 1’s.
We will rotate the number in AX along with carry by 1 bit to the right. If there is a carry we will increment counter 2. Decrement counter 1. This process with continue till all the bits are checked. The counter 2 will indicate the number of 1’s present in the word. The result of counter 2 is stored in BL.
Display the result.
eg. : AX = 5267
|
0101
|
0010
|
0110
|
0111
|
no of 1’s = 8
Algorithm to Count the Number of 1s in a Register
Step I : Initialize the data memory.
Step II : Load the number in AX register.
Step III : Initialize count in BL = 00
Initialize counter 1 = 16.
Stp IV : Rotate contents of register so that LSB will go in carry.
Step V : Check if carry = 1. If not go to step VII.
Step VI : Increment count in BL.
Step VII : Decrement counter 1.
Step VIII : Check if counter 1 = 0. If not go to step IV.
Step IX : Display result in BL.
Program to Count the Number of 1s in a Register
1 |
.model small <br/> .data <br/> a dw 5267H <br/> .code <br/> mov ax, @data ; Initialize data section <br/> mov ds, ax <br/> mov ax, a ; Load number1 in ax <br/> mov cx, 16 ; load count in cx register <br/> back: rcr ax, 1 ; rotate by 1 bit to the right <br/> jnc l1 ; if bit is 0 goto next bit <br/> inc bl ; if bit=1 increment count <br/> l1: dec cx ; decrement counter <br/> jnz back ; <br/> mov ch, 04h ; Count of digits to be displayed <br/> mov cl, 04h ; Count to roll by 4 bits <br/> l2: rol bx, cl ; roll bl so that msb comes to lsb <br/> mov dl, bl ; load dl with data to be displayed <br/> and dl, 0fH ; get only lsb <br/> cmp dl, 09 ; check if digit is 0-9 or letter A-F <br/> jbe l4 <br/> add dl, 07 ; if letter add 37H <br/> ; else only add 30H <br/> l4: add dl, 30H <br/> mov ah, 02 ; Function 2 under <br/> ; INT 21H <br/> ; (Display character) <br/> int 21H <br/> dec ch ; Decrement Count <br/> jnz l2 <br/> mov ah, 4cH ; Terminate Program <br/> int 21H <br/> end |
How to Run this Program
For Running this program you should have installed Tasm on you computer . If you have not installed Tasm yet please install from Here .
C:\programs>tasm count1.asm
Turbo Assembler Version 3.0 Copyright (c) 1988, 1991 Borland International
Assembling file: count1.asm
Error messages: None
Warning messages: None
Passes: 1
Remaining memory: 438k
C:\programs>tlink
count1
count1
Turbo Link Version 3.0 Copyright (c) 1987, 1990 Borland International
Warning: No stack
C:\programs>count1
0008
Source projectgeek.com