Z80 Routines:Optimized:PopCountA

From WikiTI
Revision as of 19:17, 15 September 2020 by Jacobly (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

This is a faster/smaller (and also obfuscated) replacement for the normal popcount a, which returns the number of set bits in a.

Typical routine:

;input: b
;output: a
;27 bytes, 108 clock cycles
TypicalPopCountA:
	ld	c,a
	xor	a
	ld	b,a
	rrc	c
	adc	a,b
	rrc	c
	adc	a,b
	rrc	c
	adc	a,b
	rrc	c
	adc	a,b
	rrc	c
	adc	a,b
	rrc	c
	adc	a,b
	rrc	c
	adc	a,b
	rrc	c
	adc	a,b

Better routine:

;- Pop Count A
;input:	byte in A
;output: number of set bits in A
;destroys BC
;22 bytes and 85 clock cycles
;author: jacobly
PopCountA:
	ld	c, a
	and	10101010b
	cpl
	rrca
	adc	a, c
	ld	b, a
	and	00110011b
	ld	c, a
	xor	b
	rrca
	rrca
	add	a, c
	ld	c, a
	rrca
	rrca
	rrca
	rrca
	add	a, c
	and	00001111b