Reputation: 484
I am a new assembly programer and I could not succeed in finding how many digits a number has.My purpose is to find factorials. I program in an emulator of assembly 8086.
Upvotes: 4
Views: 2212
Reputation: 7426
The most efficient way to perform this operation is to use the bsr
instruction (see this slides, 20 to 25).
This should make a code like this:
.text
.globl main
.type main, @function
main:
movl $1024, %eax ;; pushing the integer (1024) to analyze
bsrl %eax, %eax ;; bit scan reverse (give the smallest non zero index)
inc %eax ;; taking the 0th index into account
But, I guess you need the base 10 log and not the base 2... So, here would be the code:
.text
.globl main
.type main, @function
main:
movl $1024, %eax ;; pushing the integer (1024) to analyze
bsrl %eax, %eax ;; bit scan reverse (give the smallest non zero index)
inc %eax ;; taking the 0th index into account
pushl %eax ;; saving the previous result on the stack
fildl (%esp) ;; loading the previous result to the FPU stack (st(0))
fldlg2 ;; loading log10(2) on the FPU stack
fmulp %st, %st(1) ;; multiplying %st(0) and %st(1) and storing result in %st(0)
;; We need to set the FPU control word to 'round-up' (and not 'round-down')
fstcw -2(%esp) ;; saving the old FPU control word
movw -2(%esp), %ax ;; storing the FPU control word in %ax
andw $0xf3ff, %ax ;; removing everything else
orw $0x0800, %ax ;; setting the proper bit to '1'
movw %ax, -4(%esp) ;; getting the value back to memory
fldcw -4(%esp) ;; setting the FPU control word to the proper value
frndint ;; rounding-up
fldcw -2(%esp) ;; restoring the old FPU control word
fistpl (%esp) ;; loading the final result to the stack
popl %eax ;; setting the return value to be our result
leave
ret
I am curious to know if somebody can find better than that ! Indeed, using SSE instructions might help.
Upvotes: 2