Z80 Routines:Optimized:PopCountA

From WikiTI
Revision as of 03:17, 16 September 2020 by Jacobly (talk | contribs) (Created page with "PopCountA PopCountA This is a faster/smaller (and also obfuscated) replacement for the normal popcount a, which r...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigationJump to search
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.

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