Part of an assignment for my systems programming class asks us to write an assembly module that returns the number of digits in a 32-bit integer given a base in the range of 2 to 36 inclusive. Everything works fine except for one case. When I use the maximum signed positive 32-bit value 0x7FFFFFFF
and a base of 2
, the code returns 32 instead of 31 as the number of digits.
As a solution, I thought about handling this case by including instructions to check if the num
argument is equal to 0x7FFFFFFF
and returning 31 if so. However, I'm not sure if that approach would be correct.
I'm using a "do-while loop" type algorithm to solve the problem.
Function prototype: int numOfDigits( long num, int base );
.global numOfdigits
.section ".text"
numOfDigits:
save %sp, -96, %sp
clr %l0 ! digits = 0
mov %i0, %o0 ! num is first argument to .div
mov %i1, %o1 ! base is second argument to .div
loop:
call .div ! %o0 = %o0 / %o1
nop
inc %l0 ! ++digits
cmp %o0, 0 ! while ( num != 0 )
bne loop
nop
mov %l0, %i0 ! copy digits value into return register
ret
restore