The square number in the NASM assembly without multiplication

Is it possible to square the number stored in the register (for example, eax), without any multiplication (using shifts, etc.)? I will be hosting a 16-bit number in a 32-bit assembly, so overflow should not be a problem. I am using the NASM x86 build to create a program. Thanks in advance for your help.

+3
source share
3 answers

In C:

int square(int n) {
    int i, r = 0;
    for (i = n; i; i >>= 1, n <<= 1)
        if (i & 1)
            r += n;
    return r;
}

I will leave NASM to you.

+5
source

Shift and Add are always a good starting point for doing multiplications on computers without involving multiplication instructions.

- , .

+3

A bit late. Here is the logic: - Square N can be obtained by adding the first N odd numbers.

In C,

int sqr(int num){
    int j=1; 
    int sum=0;
    while(num>0){
        sum += j;
        j += 2; 
        num--;
    }
    return sum;
 }

but applicable only for integers.

0
source

Source: https://habr.com/ru/post/1740613/


All Articles