Reading and Printing in Assembly Stdin Stdout


2.x Introduction to the HLA Standard Library

There are two reasons HLA is much easier to larn and use than standard assembly language. The first reason is HLA's high level syntax for declarations and control structures. This HLA feature leverages your loftier level linguistic communication cognition, reducing the need to larn cabalistic syntax, allowing you to learn associates linguistic communication more efficiently. The other half of the equation is the HLA Standard Library. The HLA Standard Library provides lot of unremarkably needed, like shooting fish in a barrel to use, associates language routines that you can call without having to write this code yourself (or fifty-fifty acquire how to write yourself). This eliminates i of the larger stumbling blocks many people have when learning assembly language: the need for sophisticated I/O and support code in order to write bones statements. Prior to the advent of a standardized assembly language library, it often took weeks of study before a new assembly language developer could do as much as print a string to the display. With the HLA Standard Library, this roadblock is removed and you lot can concentrate on learning assembly linguistic communication concepts rather than learning low-level I/O details that are specific to a given operating system.

A wide variety of library routines is only role of HLA's back up. After all, assembly language libraries have been around for quite some time1. HLA's Standard Library continues the HLA tradition by providing a high level language interface to these routines. Indeed, the HLA linguistic communication itself was originally designed specifically to allow the cosmos of a high-level attainable set up of library routines2. This high level interface, combined with the loftier level nature of many of the routines in the library, packs a surprising amount of ability in an easy to apply package.

The HLA Standard Library consists of several modules organized by category. The post-obit table lists many of the modules that are availablethree:

Table 3: HLA Standard Library Modules

Name

Clarification

args

Command line parameter parsing support routines.

conv

Various conversions between strings and other values.

cset

Character ready functions.

DateTime

Agenda, date, and fourth dimension functions.

excepts

Exception handling routines.

fileio

File input and output routines

hla

Special HLA constants and other values.

Linux

Linux organisation calls (HLA Linux version only).

math

Transcendental and other mathematical functions.

retention

Retentivity allocation, deallocation, and support lawmaking.

misctypes

Miscellaneous data types.

patterns

The HLA pattern matching library.

rand

Pseudo-random number generators and support code.

stdin

User input routines

stdout

Provides user output and several other support routines.

stdlib

A special include file that links in all HLA standard library modules.

strings

HLA's powerful string library.

tables

Tabular array (associative array) support routines.

win32

Constants used in Windows calls (HLA Win32 version, merely)

x86

Constants and other items specific to the 80x86 CPU.

Later sections of this text will explain many of these modules in greater item. This section volition concentrate on the about important routines (at to the lowest degree to first HLA programmers), the stdio library.

2.10.i Predefined Constants in the STDIO Module

Possibly the get-go place to first is with a description of some common constants that the STDIO module defines for y'all. 1 constant you lot've seen already in code appearing in this chapter. Consider the following (typical) example:

stdout.put( "Hullo World", nl );             

The nl actualization at the end of this statement stands for newline. The nl identifier is not a special HLA reserved word, nor is information technology specific to the stdout.put statement. Instead, it's simply a predefined constant that corresponds to the string containing a single linefeed grapheme (the standard Windows end of line sequence).

In addition to the nl constant, the HLA standard I/O library module defines several other useful character constants. They are

  • stdio.bell The ASCII bell character. Beeps the speaker when printed.
  • stdio.bs The ASCII backspace character.
  • stdio.tab The ASCII tab character.
  • stdio.eoln A linefeed character (even under Windows).
  • stdio.lf The ASCII linefeed graphic symbol.
  • stdio.cr The ASCII carriage return character.

Except for nl, these characters appear in the stdio namespace (and, therefore, crave the "stdio." prefix). The placement of these ASCII constants within the stdio namespace is to assistance avoid naming conflicts with your own variables. The nl name does not announced inside a namespace because you will utilise it very frequently and typing stdio.nl would become wearisome very quickly.

2.10.two Standard In and Standard Out

Many of the HLA I/O routines have a stdin or stdout prefix. Technically, this means that the standard library defines these names in a namespace 4. In practice, this prefix suggests where the input is coming from (the standard input device) or going to (the standard output device). By default, the standard input device is the system keyboard. Likewise, the default standard output device is the console display. And so, in general, statements that have stdin or stdout prefixes volition read and write data on the panel device.

When you run a programme from the command line window (or shell), yous accept the choice of redirecting the standard input and/or standard output devices. A command line parameter of the form ">outfile" redirects the standard output device to the specified file (outfile). A control line parameter of the class "<infile" redirects the standard input and so that its data comes from the specified input file (infile). The following examples demonstrate how to utilize these parameters when running a plan named "testpgm" in the command windowfive:

testpgm <input.data   testpgm >output.txt   testpgm <in.txt >output.txt          

two.10.3 The stdout.newln Routine

The stdout.newln procedure prints a newline sequence to the standard output device. This is functionally equivalent to saying "stdout.put( nl );" Of course, the call to stdout.newln is sometimes a little more than convenient. Example of telephone call:

stdout.newln();          

2.10.4 The stdout.putiX Routines

The stdout.puti8, stdout.puti16, and stdout.puti32 library routines impress a single parameter (one byte, two bytes, or four bytes, respectively) as a signed integer value. The parameter may be a constant, a annals, or a memory variable, as long as the size of the actual parameter is the same as the size of the formal parameter.

These routines print the value of their specified parameter to the standard output device. These routines will print the value using the minimum number of print positions possible. If the number is negative, these routines will print a leading minus sign. Here are some examples of calls to these routines:

stdout.puti8( 123 );   stdout.puti16( DX );   stdout.puti32( i32Var );          

2.10.five The stdout.putiXSize Routines

The stdout.puti8Size, stdout.puti16Size, and stdout.puti32Size routines output signed integer values to the standard output, just similar the stdout.putiX routines. These routines, however, provide more than command over the output; they let you specify the (minimum) number of impress positions the value will require on output. These routines besides let you lot specify a padding character should the print field exist larger than the minimum needed to display the value. These routines crave the post-obit parameters:

          stdout.puti8Size( Value8, width, padchar );   				stdout.puti16Size( Value16,width, padchar );   				stdout.puti32Size( Value32, width, padchar );             

The ValueX parameter can be a abiding, a register, or a memory location of the specified size. The width parameter tin be whatsoever signed integer constant that is betwixt -256 and +256; this parameter may be a constant, register (32-scrap), or memory location (32-bit). The padchar parameter should be a single character value.

Like the stdout.putiX routines, these routines print the specified value every bit a signed integer constant to the standard output device. These routines, yet, let you lot specify the field width for the value. The field width is the minimum number of print positions these routines will utilise when press the value. The width parameter specifies the minimum field width. If the number would require more print positions (e.g., if you attempt to print "1234" with a field width of ii), and so these routines will print however many characters are necessary to properly display the value. On the other hand, if the width parameter is greater than the number of character positions required to display the value, then these routines will print some extra padding characters to ensure that the output has at least width character positions. If the width value is negative, the number is left justified in the print field; if the width value is positive, the number is right justified in the print field.

If the absolute value of the width parameter is greater than the minimum number of print positions, then these stdout.putiXSize routines volition print a padding grapheme before or after the number. The padchar parameter specifies which graphic symbol these routines will impress. Most of the time you lot would specify a space equally the pad graphic symbol; for special cases, you might specify some other character. Remember, the padchar parameter is a character value; in HLA graphic symbol constants are surrounded by apostrophes, not quotation marks. Y'all may also specify an eight-fleck register as this parameter.

Here is a brusk HLA program that demonstrates the utilize of the puti32Size routine to display a list of values in tabular class:

              program NumsInColumns;      #include( "stdlib.hhf" );      var       i32:    int32;       ColCnt: int8;      begin NumsInColumns;          mov( 96, i32 );       mov( 0, ColCnt );       while( i32 > 0 ) practise              if( ColCnt = viii ) and so                  stdout.newln();               mov( 0, ColCnt );              endif;           stdout.puti32Size( i32, v, ` ` );           sub( 1, i32 );           add( 1, ColCnt );          endwhile;       stdout.newln();      stop NumsInColumns;      Program ii.4	 Columnar Output Demonstration Using stdio.Puti32Size          

2.10.6 The stdout.put Routine

The stdout.put routinesix is i of the well-nigh flexible output routines in the standard output library module. Information technology combines most of the other output routines into a single, easy to use, process.

The generic grade for the stdout.put routine is the post-obit:

          stdout.put(          list_of_values_to_output          );          

The stdout.put parameter list consists of one or more than constants, registers, or memory variables, each separated past a comma. This routine displays the value associated with each parameter appearing in the list. Since we've already been using this routine throughout this chapter, yous've already seen lots of examples of this routine's basic form. It is worth pointing out that this routine has several additional features not credible in the examples appearing in this chapter. In particular, each parameter tin take ane of the post-obit ii forms:

value

value:width

The value may exist whatsoever legal constant, register, or retentiveness variable object. In this chapter, you've seen cord constants and retentiveness variables appearing in the stdout.put parameter list. These parameters correspond to the showtime grade above. The second parameter form in a higher place lets yous specify a minimum field width, similar to the stdout.putiXSize routines7. The following sample program produces the same output as the previous program; however, it uses stdout.put rather than stdout.puti32Size:

              programme NumsInColumns2;      #include( "stdlib.hhf" );      var       i32:    int32;       ColCnt: int8;      begin NumsInColumns2;          mov( 96, i32 );       mov( 0, ColCnt );       while( i32 > 0 ) exercise              if( ColCnt = 8 ) then                  stdout.newln();               mov( 0, ColCnt );              endif;           stdout.put( i32:5 );           sub( 1, i32 );           add( one, ColCnt );          endwhile;       stdout.put( nl );      end NumsInColumns2;      Program two.5	 Demonstration of stdout.put Field Width Specification          

The stdout.put routine is capable of much more the few attributes this section describes. This text will innovate those additional capabilities as appropriate.

two.10.vii The stdin.getc Routine.

The stdin.getc routine reads the adjacent bachelor character from the standard input device's input bufferviii. It returns this character in the CPU's AL register. The post-obit example program demonstrates a simple use of this routine:

              program charInput;      #include( "stdlib.hhf" );      var       counter: int32;      begin charInput;                  // The following repeats as long as the user       // confirms the repetition.              repeat                  // Print out 14 values.                      mov( 14, counter );           while( counter > 0 ) practice                          stdout.put( counter:3 );               sub( 1, counter );                          endwhile;                      // Expect until the user enters `y' or `northward'.                      stdout.put( nl, nl, "Do you wish to see information technology again? (y/northward):" );           forever                          stdin.readLn();               stdin.getc();               breakif( al = `n' );               breakif( al = `y' );               stdout.put( "Error, please enter only `y' or `n': " );                          endfor;           stdout.newln();                  until( al = `n' );                  cease charInput;      Plan 2.half-dozen	 Demonstration of the stdin.getc() Routine          

This program uses the stdin.ReadLn routine to strength a new line of input from the user. A clarification of stdin.ReadLn appears merely a little later in this chapter.

2.10.8 The stdin.getiX Routines

The stdin.geti8, stdin.geti16, and stdin.geti32 routines read eight, 16, and 32-chip signed integer values from the standard input device. These routines return their values in the AL, AX, or EAX annals, respectively. They provide the standard mechanism for reading signed integer values from the user in HLA.

Like the stdin.getc routine, these routines read a sequence of characters from the standard input buffer. They begin by skipping over any white infinite characters (spaces, tabs, etc.) and then catechumen the following stream of decimal digits (with an optional, leading, minus sign) into the corresponding integer. These routines heighten an exception (that you can trap with the Endeavour..ENDTRY statement) if the input sequence is non a valid integer string or if the user input is also big to fit in the specified integer size. Note that values read past stdin.geti8 must be in the range -128..+127; values read by stdin.geti16 must exist in the range -32,768..+32,767; and values read by stdin.geti32 must be in the range -2,147,483,648..+2,147,483,647.

The following sample program demonstrates the employ of these routines:

              program intInput;      #include( "stdlib.hhf" );      var       i8:     int8;       i16:    int16;       i32:    int32;      begin intInput;              // Read integers of varying sizes from the user:                  stdout.put( "Enter a small-scale integer between -128 and +127: " );       stdin.geti8();       mov( al, i8 );              stdout.put( "Enter a small integer between -32768 and +32767: " );       stdin.geti16();       mov( ax, i16 );              stdout.put( "Enter an integer between +/- two billion: " );       stdin.geti32();       mov( eax, i32 );              // Display the input values.              stdout.put       (           nl,            "Hither are the numbers you entered:", nl, nl,           "Viii-fleck integer: ", i8:12, nl,           "16-bit integer:    ", i16:12, nl,           "32-bit integer:    ", i32:12, nl       );                                end intInput;      Program 2.7	 stdin.getiX Case Code          

Y'all should compile and run this program and test what happens when you enter a value that is out of range or enter an illegal string of characters.

2.10.9 The stdin.readLn and stdin.flushInput Routines

Whenever you phone call an input routine similar stdin.getc or stdin.geti32, the plan does not necessarily read the value from the user at that moment. Instead, the HLA Standard Library buffers the input past reading a whole line of text from the user. Calls to input routines will fetch information from this input buffer until the buffer is empty. While this buffering scheme is efficient and convenient, sometimes it can be disruptive. Consider the post-obit code sequence:

stdout.put( "Enter a small integer between -128 and +127: " );   stdin.geti8();   mov( al, i8 );          stdout.put( "Enter a small integer between -32768 and +32767: " );   stdin.geti16();   mov( ax, i16 );             

Intuitively, you would expect the program to impress the commencement prompt message, wait for user input, impress the second prompt message, and wait for the 2nd user input. However, this isn't exactly what happens. For example if you run this code (from the sample program in the previous section) and enter the text "123 456" in response to the start prompt, the program will non cease for additional user input at the 2d prompt. Instead, it will read the second integer (456) from the input buffer read during the execution of the stdin.geti8 call.

In full general, the stdin routines only read text from the user when the input buffer is empty. As long as the input buffer contains additional characters, the input routines will attempt to read their data from the buffer. You may take reward of this behavior by writing code sequences such as the post-obit:

stdout.put( "Enter ii integer values: " );   stdin.geti32();   mov( eax, intval );   stdin.geti32();   mov( eax, AnotherIntVal );             

This sequence allows the user to enter both values on the aforementioned line (separated past 1 or more white space characters) thus preserving space on the screen. So the input buffer behavior is desirable every now and and then.

Unfortunately, the buffered beliefs of the input routines is definitely counter-intuitive at other times. Fortunately, the HLA Standard Library provides ii routines, stdin.readLn and stdin.flushInput, that let you control the standard input buffer. The stdin.readLn routine discards everything that is in the input buffer and immediately requires the user to enter a new line of text. The stdin.flushInput routine simply discards everything that is in the buffer. The next time an input routine executes, the system will require a new line of input from the user. You lot would typically phone call stdin.readLn immediately before some standard input routine; you would unremarkably call stdin.flushInput immediately after a call to a standard input routine.

Note: If you are calling stdin.readLn and y'all find that you are having to input your information twice, this is a proficient indication that you should be calling stdin.flushInput rather than stdin.readLn. In general, you should always exist able to call stdin.flushInput to flush the input buffer and read a new line of data on the next input telephone call. The stdin.readLn routine is rarely necessary, then you should use stdin.flushInput unless you really need to immediately force the input of a new line of text.

2.10.10 The stdin.go Macro

The stdin.get macro combines many of the standard input routines into a single call, in much the same style that stdout.put combines all of the output routines into a single call. Actually, stdin.get is much easier to apply than stdout.put since the but parameters to this routine are a list of variable names.

Let's rewrite the case given in the previous section:

stdout.put( "Enter ii integer values: " );   stdin.geti32();   mov( eax, intval );   stdin.geti32();   mov( eax, AnotherIntVal );             

Using the stdin.get macro, we could rewrite this code as:

stdout.put( "Enter two integer values: " );   stdin.get( intval, AnotherIntVal );             

Every bit you can run across, the stdin.become routine is a little more convenient to utilize.

Note that stdin.go stores the input values direct into the memory variables yous specify in the parameter list; it does not return the values in a register unless you actually specify a annals equally a parameter. The stdin.get parameters must all exist variables or registers9.

2.11 Putting It All Together

This chapter has covered a lot of basis! While you've still got a lot to learn near assembly language programming, this affiliate, combined with your noesis of high level languages, provides just plenty data to permit you start writing existent assembly language programs.

In this affiliate, you've seen the basic format for an HLA program. Y'all've seen how to declare integer, graphic symbol, and boolean variables. You have taken a await at the internal organization of the Intel 80x86 CPU family unit and learned nigh the MOV, ADD, and SUB instructions. Yous've looked at the basic HLA loftier level language command structures (IF, WHILE, Repeat, FOR, BREAK, BREAKIF, FOREVER, and Attempt) every bit well as what constitutes a legal boolean expression in these statements. Finally, this chapter has introduced several commonly-used routines in the HLA Standard Library.

You might think that knowing merely iii automobile instructions is inappreciably sufficient to write meaningful programs. All the same, those three instructions (mov, add, and sub), combined with the HLA loftier level control structures and the HLA Standard Library routines are actually equivalent to knowing several dozen machine instructions. Certainly plenty to write simple programs. Indeed, with only a few more than arithmetic instructions plus the ability to write your own procedures, you'll be able to write almost whatsoever programme. Of grade, your journey into the world of assembly language has only just begun; you lot'll acquire some more instructions, and how to use them, starting in the next chapter.

iE.g., the UCR Standard Library for 80x86 Assembly Linguistic communication Programmers.

2HLA was created because MASM was insufficient to support the creation of the UCR StdLib v2.0.

3Since the HLA Standard Library is expanding, this list is probably out of date. Please see the HLA documentation for a current list of Standard Library modules.

4Namespaces will exist the bailiwick of a later chapter.

5Note for Linux users: depending on how your system is prepare, yous may need to type "./" in front end of the program'southward name to actually execute the plan, east.g., "./testpgm <input.data".

6 Stdout.put is actually a macro, not a procedure. The distinction between the 2 is beyond the scope of this chapter. However, this text will describe their differences a trivial later on.

7Note that you cannot specify a padding grapheme when using the stdout.put routine; the padding character defaults to the space character. If you need to apply a dissimilar padding character, phone call the stdout.putiXSize routines.

viii"Buffer" is just a fancy term for an array.

9Note that register input is always in hexadecimal or base 16. The next chapter volition discuss hexadecimal numbers.

Web Site Hits Since
Jan 1, 2000


deckercappira56.blogspot.com

Source: https://www.plantation-productions.com/Webster/www.artofasm.com/Linux/HTML/HelloWorlda4.html

0 Response to "Reading and Printing in Assembly Stdin Stdout"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel