Search code examples
arraysassemblyemu8086

How can we obtain array length in emu8086 assembly?


I want to obtain the array length in assembly for emu8086. With length or sizeof I get an error:

error-wrong parameter

Can anyone help me with other ways to find the length of an array?


Solution

  • A. You can calculate the difference between the end of the array ($) and its start (offset array1). You need to do the calculation right after the array definition. If you didn't, $ would already be pointing much further down in the program.

    array1 db 65,66,67
    array1len equ $ - offset array1
    
    array2 db 'Any string is an array too!'
    array2len equ $ - offset array2
    

    B. If the array is known to have some special terminating value, then searching for that value is also a way to find the length of the array. Consider an ASCIIZ string, a string of ASCII characters terminated by a zero byte:

    string db 'Just a text.', 0
    

    Next loop will produce the length (12, not including the zero byte of course) in CX:

      mov  si, offset string - 1
    back:
      inc  si
      cmp  byte ptr [si], 0
      jne  back
      lea  cx, [si - offset string]