The amateur programmer
The amateur programmer

Reputation: 1308

x86-64 mul instruction does not multiply properly?

I'm having weird problem with the MUL instruction on x86-64. It seems like the instruction does not properly multiply the 64 bit stuff in the register. I'm trying to make a simple code that just raises the 2 to a power defined by the caller (passed in RDI). The value in RAX seems to get stuck at a magical 28 limit for some reason. I'm probably again missing something very obvious here (probably misunderstood something about the instruction itself). Below is my code and output attached:

twotopwr:
    ;RDI contains the power
    CALL printfcall ;this prints the good value of 10 when testing with number 10 in RDI
    MOV RAX, 2;The 2 here
    PUSH RBX
    MOV RBX, 2;Multiplier
    CMP RDI, 0;If 0 then return 1
    JE ret1

loop:
    ;CALL printfcall
    DEC RDI ;Subtract the exponent
    CMP RDI, 0 ;Check if 0
    JE ret ;if 0 then return the value in rax
    MUL RBX ;Multiply rax by 2
    ;Print the rax content
    PUSH RDI
    MOV RDI, RAX
    CALL printfcall ;Debugging print
    POP RDI

    JMP loop ;Again
ret1:
    MOV RAX, 1;Exponent was 0
ret:
    POP RBX
    ;return value in rax
    RET

Outputs

The int is 10
The int is 4
The int is 26
The int is 28
The int is 28
The int is 28
The int is 28
The int is 28
The int is 28
The int is 28

My printing function:

printfcall:;Pass in RDI

        MOV RSI, RDI
        PUSH RDI
        MOV RDI, formatStrdec
        MOV AL, 0 
        CALL printf
        POP RDI
        RET

Upvotes: 1

Views: 701

Answers (1)

Eraklon
Eraklon

Reputation: 4288

The printf will return the number of characters printed out in the RAX register which is 13 after printing this The int is 4 first, that is why you get 26 in next iteration and that iteration printf returns 14 as written character number, which is 28 after multiplication by 2 and this is going on over and over again.

Upvotes: 3

Related Questions