- 8051

8051 code to find number of zeros and ones in a given number…!!

In this article let’s learn how to find the number of zeros and ones in a number. The easy way to find the number of zeros is by rotating each bit with carry and checking whether the carry flag is set or reset.

 Algorithm:

1) Initializing R0 to the numbers to be checked and R1 to the number of bits to be checked.
2) Left or Right rotating the number with carry.
3) Checking whether the carry has zero or one.
4) If the carry is one then incrementing the counter for one and if the carry is zero then incrementing       the counter for one.
5) Checking the number of bits and repeating the above steps till the goal is reached.
This program finds the number of zeros and ones in binary equivalent number.

 Code goes here:

ORG 0000h
LJMP MAIN
ORG 40h
MAIN:  MOV R0,#12    ; number to be checked whether zero or one
       MOV R1,#08    ; number of bits to be checked
       MOV A,R0
LOOP:  RLC A         ; left rotating it to check each bit of number
       JC LABEL1     ; if the bit is one jumping to one's counter
       INC R2        ; incrementing the counter for zero bit
       SJMP LABEL2
LABEL1:INC R3        ;incrementing the counter for zero bit
LABEL2:DJNZ R1,LOOP  ; checking the counter of bits
       END

Leave a Reply