Reputation: 332
I try to do a branch table in assembly 8086.
I wrote it:
org 100h
; START THE PROGRAM
mov si, 1
jmp cs:table[si]
table dw C1, C2, C3
C1:
add bx, 1
jmp EXIT
C2:
add bx, 2
jmp EXIT
C3:
add bx, 3
jmp EXIT
C4:
add bx, 4
jmp EXIT
; EXIT PRORGRAM
EXIT:
mov ah, 0
int 16h
ret
The code not working, It's jump to the incorrect label.
Someone can give me example or fix my code ?
Upvotes: 3
Views: 2516
Reputation: 44046
Be careful that
jmp cs:table[si]
actually is a mangled version of
jmp cs:[table + si]
It is not an array indexing.
The assembly language has no types, to avoid confusion don't use such an unorthodox syntax.
Suppose table
starts at 1000h. Then
With SI = 1
the offset to jump to is taken at 1000h + 1 = 1001h.
The WORD at that location occupies 1001h and 1002h, thus it crosses C1 and C2.
Using the index directly to access an array is a comfort not available in assembly, we need to scale the index based on the size of the items.
In this case each item is a WORD, 2 bytes, so the index must be scaled by 2.
Index Scaled index Address accessed
0 0 1000h
1 2 1002h
2 4 1004h
Thus
mov si, 1
shl si, 1 ;Scale index, SI = SI*2^1 = SI*2
jmp cs:table[si]
or better, if the index is known at "compile time"
mov si, 2 ;Use scaled index directly
jmp cs:table[si]
Upvotes: 10