Homework 6

Print Integer in Any Base

Note: This assignment requires outputting single characters to the display. Check out a function named WriteChar in the irvine32 library.

The following displays the character 'A' to the screen:
Mov       Al, 'A'
Call        WriteChar

Overview - As we have seen in our program development, display of numeric values in hexadecimal and binary bases is often more useful than as a decimal value. While C++ does not provide general numeric output routines it is relatively straightforward, particularly in Assembly language, to implement a generalized routine outputting integers in any base. The algorithm is based upon the method described in class for conversion of base 10 to other bases using repeated division. For example, to convert 1310 to base 2 the remainder is written in right-to-left order:

```         6          3           1          0                  Result:  11012
2 / 13       2/ 6        2/ 3       2/ 1
-12         -6          -2         -0
1          0           1          1```
Notice that the result is produced reversed from the order the digits must be printed. The result is produced as 1011 but must be printed reversed as 1101. This reversal can be easily accomplished by:
1. pushing the remainder onto the stack after each division,
2. when the quotient is 0, pop off each remainder and print.
Assignment
• Implement a putAnyBase output routine in Assembler using parameter passing methods of:
1. call-by-value
2. call-by-reference
• The output should be the same for the execution of both programs.
• The putAnyBase should not make use of global variables.
Turn in
1. Cover Page - Your name, date, and Homework 6. Staple all pages together.
2. Assembler program (what you typed in) for:
3. [please submit 2 copies of your code, one for each version!]
1. call-by-value
2. call-by-reference
4. Output - Test using inputs of:
1. 2 12 24
2. 16 12 24
3. 20 12 24
4. 16  32767  32768
5. 2  32767  32768
6. 2 1 4294967294
7. 14 19 89
8. 21 21 41

C++ Example Algorithm

```#include <iostream.h>
void putAnyBase( int base; int n) {
int q, r, i;                    // May use registers for q, r, and i
// or allocate dynamic variables on stack
q = n;
i = 0;
do {                            // Convert from base 10 to desired base
r = q % base;
q = q / base;
push( r );                   // Save remainder right to left order
i++;
} while (q != 0)

for ( ; i>0; i--){              // Recover remainder, print left to right
r = pop;
if (r < 10)
PutChar('0'+r);            // Print character '0'..'9'
else PutChar('A'+r-10);      // or 'A'..'Z'
}
}

void main(void) {
int base, n1, n2;
cin >> base >> n1 >> n2;        // Read output base and two integers
putAnyBase( base, n1 );         // Output n1 in base
cout << '+';
putAnybase( base, n2 );
cout << '=';
putAnyBase( base, n1+n2 );      // Output sum of n1 and n2 in base
}```