Assembly language is known for its obscurity and complexity, but this tutorial looks at it from a different perspective—it is a language that provides almost all the information. Programmers can see everything that is happening, including the registers and flags in the CPU! However, with this capability, programmers must handle the details of data representation and instruction formatting. Programmers work at a level with a lot of details. Now, let’s take a simple assembly language program as an example to understand how it works. The program adds two numbers and stores the result in a register. The program is named AddTwo:
main PROC mov eax, 5 ; Move the number 5 into the eax register add eax, 6 ; Add 6 to the eax register INVOKE ExitProcess, 0 ; End the programmain ENDP
Now let’s take a closer look at this program line by line:
-
The first line starts the main program, which is the entry point of the program;
-
The second line moves the number 5 into the eax register;
-
The third line adds 6 to the value in EAX, resulting in a new value of 11;
-
The fifth line calls the Windows service (also known as a function) ExitProcess to stop the program and return control to the operating system;
-
The sixth line marks the end of the main program.
You may have noticed the comments included in the program, which always start with a semicolon. Some declarations are omitted at the top of the program, which will be explained later, but essentially, this is a usable program. It will not display all information on the screen, but with the help of a debugger tool, the programmer can execute the program line by line and view the values in the registers.
Add a Variable
Now let’s make this program a bit more interesting by storing the result of the addition in a variable called sum. To achieve this, we need to add some labels or declarations to identify the code and data sections of the program:
.data ; This is the data sectionsum DWORD 0 ; Define a variable named sum.code ; This is the code sectionmain PROC mov eax,5 ; Move the number 5 into the eax register add eax,6 ; Add 6 to the eax register mov sum,eax ; Move the value of eax into sum INVOKE ExitProcess,0 ; End the programmain ENDP
The variable sum is declared on the second line, with a size of 32 bits, using the keyword DWORD. There are many such size keywords in assembly language, which function somewhat like data types.
However, compared to types that programmers may be familiar with, they are not as specific, such as int, double, float, etc. These keywords only limit the size and do not check the contents stored in the variable. Remember, the programmer has complete control. By the way, the code and data sections marked by the .code and .data pseudo-instructions are called segments. That is, the program has a code segment and a data segment.