Software - Counting Bits
Here are two ways to count the number of bits that are set (i.e. the number of bits that are ones) in a byte:
This routine returns the result in the accumulator.
LSR
BCC .1
ADC #$3F
.1 LSR
BCC .2
ADC #$1F
.2 LSR
BCC .3
ADC #$0F
.3 LSR
BCC .4
ADC #7
.4 LSR
BCC .5
ADC #3
.5 LSR
BCC .6
ADC #1
.6 LSR
ADC #0
This routine returns the result in the X register.
LDX #$FF
.1 INX
.2 ASL
BCS .1
BNE .2
page revision: 0, last edited: 19 Jun 2010 20:10