Search code examples
assemblynasmfasm

How to use large numbers?


How to use large numbers in? like 3441881739,30000000 etc

mov eax,3441881739

In this case eax value is a negative number. How to fix it? split it? how? I need to do also add/sub/mul/div etc the cmp operation.

Can someone explain and give an example how to do it?

I marked fasm and nasm tags but anothers assembly are welcome too. I'm on 32-bit machine.


Solution

  • If you want to deal with numbers larger than 232-1, you'll need to do multiple-precision arithmetic. For example, to add a pair of 64-bit numbers you could do something like this:

    mov eax, A_1    ; essentially C = A + B
    mov edx, B_1
    add eax, edx    ; note that for the low word, we just add
    mov C_1, eax
    mov eax, A_2
    mov edx, B_2
    adc eax, edx    ; but for the high word, we add with carry
    mov C_2, eax
    

    Having access to the carry bit means that this is considerably simpler than with most higher level languages. There's also a subtract with borrow to make multi-word subtraction easy as well. Multiplication and division depend a little. A normal 32x32 bit multiplication produces a 64-bit result (low word in eax, high word in edx). If you want something like 64x64 bit multiplication (giving a 128-bit result) you'll need to implement that yourself.

    For example, multiplication (without using the built-in mul/imul instructions) can be done something like this:

    mult proc
    ; multiplies eax by ebx and places result in edx:ecx
        xor ecx, ecx
        xor edx, edx
    mul1:
        test ebx, 1
        jz  mul2
        add ecx, eax
        adc edx, 0
    mul2:
        shr ebx, 1
        shl eax, 1
        test ebx, ebx
        jnz  mul1
    done:
        ret
    mult endp