8086 Assembly Program to Compute the Power of a Number
This blog post details an 8086-assembly program that computes the power of a number, specifically baseexponent. This example demonstrates fundamental assembly concepts like loops, multiplication, and register manipulation to perform iterative arithmetic. Let’s get started! data segment base dw 0003h exponent dw 0004h result dd ? data ends code segment assume cs:code, ds:data start: ; Initialize data segment mov ax, data mov ds, ax ; Initialize result to 1 (R = B^0) mov word ptr result, 0001h mov word ptr result+2, 0000h ; Load base and exponent mov cx, exponent ; CX = exponent (loop counter) mov bx, base ; BX = base cmp cx, 0000h je exit ; If exponent is 0, result is already 1. Jump to exit. power_loop: ; Multiply result by base ; The result is a 32-bit number in result[0] (lower word) and result[2] (upper word) ; Multiplication requires careful handling of the 32-bit result with a 16-bit multiplier. ; 1. Multiply the lower word of result by base mov ax, word ptr result ; AX = result[0] mul bx ; AX * BX -> DX:AX (32-bit product) push dx ; Save the higher word (DX) of the product mov word ptr result, ax ; Store the lower word (AX) of the product as the new result[0] ; 2. Multiply the upper word of result by base mov ax, word ptr result+2 ; AX = result[2] mul bx ; AX * BX -> DX:AX (32-bit product) ; 3. Add the two 16-bit 'carry' terms pop cx ; Retrieve the saved higher word (DX) from step 1 into CX add ax, cx ; AX = AX + CX (Sum of two high words) adc dx, 0000h ; DX = DX + 0 + Carry from the previous ADD (final carry from the 32-bit multiplication) ; 4. Store the final upper word mov word ptr result+2, ax ; Store AX as the new result[2] ; Handle the 32-bit overflow (DX is the final carry from the 32-bit multiplication) ; For a 32-bit result storage, this program assumes the result fits in 32-bits. ; If the power is large, overflow might occur, which is a limitation of this 32-bit storage approach. loop power_loop ; Decrement CX and jump back to power_loop if CX != 0 exit: int 3 ; Program termination code ends end start