Search code examples
assemblyx86masm

attach a character to string in assembly


I want to attach '$' to end of array of bytes for printing by int I tried with this code using masm:

.MODEL small
.STACK 200h
.data
m2 db "gggg"
.code
_start:
    mov ax,@data
    mov ds,ax 
    m3 db m2,"$"
END _start

but gives me this error:

 error A2071: initializer magnitude too large for specified size

is this code true? is any way to do this?


Solution

  • db is not some magic operator that would combine or concatenate different objects. It's a directive telling the assembler to allocate space (memory) statically, right here for the fixed number of the byte values in the list that follows and initialize it with those values. Hence, m2 db "gggg" gets replaced with 4 bytes, each being the ASCII code of the letter g.

    m2 is not a byte value. It's a label, a name and an address of some object. The value of this label (the address) typically does not fit into a single byte (and that's why you get the error). And you don't want the address of m2 in m3 db m2, you want the contents or the value of the object that goes by name of m2, "gggg".

    So, m3 db m2 is not going to magically expand into something like m3 db "gggg". If you want to manipulate the source code of your program and perform textual substitution, you can use macros, which have the ability to expand into numerical constants, character strings and instructions before the source code gets converted into machine code.

    In this case, however, you need to explicitly allocate another piece of space (and yes, db can do that), write code (instructions) to copy "gggg" from another location to it and then stick "$" at the end.

    Finally, something like this is almost always wrong:

    mov ds, ax
    m3 db "gggg$"
    

    When this gets translated into machine code and then executed, what do you think the CPU will do once it's done with mov ds, ax? Don't you think it will try to reinterpret the five data bytes of "gggg$" as instruction bytes, decode them and execute them just as it does with the bytes of mov ds, ax? The CPU wouldn't know that you intended those five bytes to be data and not code. Data bytes are indistinguishable from instruction bytes and db itself is not a CPU instruction, it's only a directive to the assembler just like the keyword var in Pascal or JavaScript.

    You must move the data out of the way where the CPU executes instructions. Or it will attempt to interpret data as instructions and your program won't work.