Write a short assembly subroutine to count the number of one
Solution
In this subroutine called count_ones, we use the instruction btfsc (syntax: btfsc reg, b). This instruction checks if the bit \'b\' of the register \'reg\' is 0. If it is zero, then the succeeding instruction is not executed (the control skips the succeeding instruction and executes the next instruction) and an \'nop\' (no operation) is executed instead. Otherwise, the instruction after btfsc is executed. Hence, whenever the bit is 1, the next instruction is executed and not skipped. We can utilize this instruction by using the Increment operator to increase the count of the variable NUM_ONES using \'incf\'.
The bit to be checked starts from 0th bit to the 3rd bit. Overall, the operation of checking the bits has to be done 4 times.
count_ones
COUNT equ 04h;
BIT equ 00h;
NUM_ONES equ 00h;
again: btfsc TEMP_1,BIT;
incf NUM_ONES;
incf BIT;
decfsz COUNT;
goto again;
return;
