We had an assignment in Hardware/Software programming, where we had to make a program in assembler, which can count the number of 1′s in a 16-bit binary string. The sollution for this in the book, Introduction to computing systems – from bits & gates to C & beyond by Yale N. Patt and Sanjay J. Patel, was 12 instructions, we shorted it down to 4 instructions, if you don’t count the initialization part, as seen in the code below. The code is made for the LC-3 processor.
; Assignment 7.7
; Instruction set is from the LC-3 processor.
; This program counts the 1's in the 16-bit binary number, which is located in R0.
; We can do it easily since the Branch instrcution looks at the Most Significant Bit
; and by checking for whether that is 1 or 0 we can either count or not.
; In the end we check if R0 has become 0.
; Made by Tomasz Cielecki & Benjamin Bennike, HW/SW Semester 3 F09 DTU
.ORIG x3000
LD R1, ZERO ;The order of initialization is important,
LD R0, NUMBER ;since BR looks at the last modified register.
TEST BRp TEST2
ADD R1, R1, #1
TEST2 ADD R0, R0, R0 ;Left shift NUMBER for next comparison.
BRnp TEST
HALT
ZERO .FILL x0000
NUMBER .FILL x1370 ;Contains the number to be 1's counted.
.END
Here is a block diagram for you too look at, for better understanding of the code.
