Question

I want to make a subroutine in .asm that can see if a number given in the terminal is or isn't a square of two .

i.e: I choose the number 5, is 2^x = 5? My subroutine will make several divisions to check if the rest of the division is 0 or 1, and that is what will tell me if 5 is or isn't a square of two.

For example, in C I wrote this code:

    int square(int val){

        while (((val % 2) == 0) && val > 1)
            val = val/2;

        if(val == 1)
            return 1;

        else
            return 0;
    }

What is the equivalent in assembly?

Was it helpful?

Solution

Given that you don't specify a particular compiler for asm , I will post you an example for asm51 compiler, used for intel uC 8051:

       org 00H            ;start directive
       VAL equ R2         ;assuming that value of interest is in R2 register      
       COUNTER equ R3   

       mov COUNTER,#8D    ;initialise the counter
       mov A,VAL          ;store in the accumulator 
                          ;the value you want to check if is power of two 
LOOPi: jb Acc,7,NEXT      ;if bit 7 of value is 1 jump to NEXT tag
LOOPj: rl A               ;rotate bit 7 of acumulator to left
       djnz COUNTER,LOOPi ;decrease COUNTER and check another bit if counter != 0
       jmp FINISH         ;jump to finish if counter == 0

NEXT:  inc COUNTER        
       jmp LOOPj

FINISH:cjne COUNTER,#1D,SOME      ;if counter == 1 then value is power of 2     
       ;;;;;;here you do whatever you have to do if is power of two
SOME:
       ;;;;;;here you do whatever you have to do if it is not power of two

Basically what I am doing here is checking for the case of only one 1 in my 8 bits, if that is the case I have a power of two:

Remember:

0000 0001 = 1 = power(2,0)
0000 0010 = 2 = power(2,1)
0000 0100 = 4 = power(2,2)
0000 1000 = 8 = power(2,3)
0001 0000 = 16 = power(2,4)
0010 0010 = 32 = power(2,5)
0100 0010 = 64 = power(2,6)
1000 0000 = 128 = power(2,7)

As you probably have noticed, this example is limited to only 7 powers of two, but that will be different for other architecture, due to the register's size, in this particular case 8051 register's are of only 1 byte. Hope it helps. Cheers

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top