Count BitsΒΆ
Counts the number of set bits (1s) in a value.
1; Count bits: count set bits in 0b10110101 (181)
2; Output: R16 = 5
3
4start:
5 ldi r17, 181 ; input = 0b10110101 (5 set bits)
6 ldi r16, 0 ; count = 0
7 mov r18, r17 ; working copy
8
9loop:
10 ; check if value is zero
11 cpi r18, 0
12 breq done
13
14 ; if LSB is 1, increment count
15 mov r19, r18
16 ldi r20, 1
17 and r19, r20
18 cpi r19, 1
19 brne no_inc
20 inc r16
21
22no_inc:
23 ; shift right (divide by 2)
24 ldi r20, 2
25 div r18, r20
26
27 jmp loop
28
29done:
30 jmp done
Demonstrates bit manipulation and counting operations.