wizard
wizard

Reputation: 21

Create a MASM program that converts the temperature from Celsius to Fahrenheit

I keep getting an "Integer overflow" on line idiv dword ptr [NINE]. Is there another way I can rewrite this to get my MASM to run properly and give me the answer 59°F in memory?

.386
.model flat, stdcall
.stack 4096
ExitProcess PROTO, dwExitCode:DWORD

.data
CelsiusTemperature DWORD 32

.code

; Function to convert Celsius to Fahrenheit
; Input: ecx - Celsius temperature
; Output: eax - Fahrenheit temperature
_convertC2F PROC
    push ebp                ; save the base pointer
    mov ebp, esp            ; set up the new base pointer
    sub esp, 4              ; reserve space for the return value
    mov eax, ecx            ; move the Celsius temperature to eax
    imul eax, 9             ; multiply by 9
    idiv dword ptr [NINE]   ; divide by 5
    add eax, 32             ; add 32 to get the Fahrenheit temperature
    mov dword ptr [ebp-4], eax ; store the Fahrenheit temperature on the stack
    mov eax, [ebp-4]        ; move the Fahrenheit temperature to eax
    mov esp, ebp            ; restore the stack pointer
    pop ebp                 ; restore the base pointer
    ret                     ; return from the function
_convertC2F ENDP

main PROC
    mov ecx, CelsiusTemperature ; set the Celsius temperature to the value in data
    call _convertC2F        ; call the function to convert to Fahrenheit
    ; eax now contains the Fahrenheit temperature
    ; do something with it here
    INVOKE ExitProcess, 0   ; exit the program
main ENDP

NINE DWORD 5

END main

Upvotes: 1

Views: 60

Answers (1)

Sep Roland
Sep Roland

Reputation: 39166

NINE DWORD 5

It is strange to assign the value 5 to a variable named NINE (9).
Also, why didn't you put this variable in the .data section where you already have a CelsiusTemperature variable?

mov eax, ecx            ; move the Celsius temperature to eax
imul eax, 9             ; multiply by 9
idiv dword ptr [NINE]   ; divide by 5
add eax, 32             ; add 32 to get the Fahrenheit temperature

The error that you report exists because the idiv dword ptr [NINE] instruction divides the register combo EDX:EAX and you forgot to initialize EDX beforehand.

; Function to convert Celsius to Fahrenheit
; Input: ECX - Celsius temperature
; Output: EAX - Fahrenheit temperature
; Clobbers: EDX
_convertC2F PROC
    imul eax, ecx, 9      ; multiply Celsius by 9, store to EAX
    cdq                   ; sign-extend EAX into EDX:EAX
    idiv dword ptr [FIVE] ; signed division of EDX:EAX by 5
    add  eax, 32          ; add 32 to get Fahrenheit
    ret                   ; return from the function
_convertC2F ENDP

Because you call your _convertC2F function with a register argument (ECX) and return the result in EAX, there's no need to include those prologue/temp/epilogue codes in the function.

Upvotes: 1

Related Questions