Difference between revisions of "Z80 Routines:Math:Logarithm"

From WikiTI
Jump to: navigation, search
(created, includes log of base 2)
 
m (fix formatting)
Line 2: Line 2:
 
[[Category:Z80 Routines|Logarithm]]
 
[[Category:Z80 Routines|Logarithm]]
  
== Introduction ==
+
= Introduction =
  
= Integer Log of base 2 ==
+
== Integer Log of base 2 ==
  
 
  <nowiki>
 
  <nowiki>

Revision as of 02:26, 29 May 2010


Introduction

Integer Log of base 2

; input: hl (16-bit integer unsigned)
; output: a = log2(hl) (rounded down and from -1 to 15) (8-bit integer signed)
log2:
	ld a,h
	or l
	ld a,-1
	ret z     ; return -1 if hl=0
	ld b,15   ; logarithm in base 2 is the number of significant bits for a integer, i.e. number of bits after the first 1 including it
log2loop:
	add hl,hl
	jr c,log2end
	djnz log2loop
log2end:
	ld a,b
	ret
 

Integer Log of base 10

Since log10=log2(hl)/log2(10). We can multiply by 1/log2(10).


 

Integer Log of base B

The same trick as above.

;unfinished
logB:
; input: hl = number
;	 b = base
; output: a = log hl base b
	
	ret