How to print a TWO-digit number ?
 

  • We just learned how to print a one-(decimal)-digit number

  • To print a TWO-(decimal)-digit number, we can do the following:

      • Obtain the individual digits of the (decimal) number

            First digit = number / 10
            2nd   digit = number % 10         
          

      • Convert each individual digits into one-digit strings

      • Concatenate the digit-strings

Converting a TWO-digits 2's compl repr to it's string representation

Illustrative example:

  • Input number = 00001100 (represents the decimal number 12)

  • We can obtain the individual digits of the decimal number 12 as follows:

       Computation performed internally in the computer:      
      
          00001100 / 00001010 = 00000001
          00001100 % 00001010 = 00000010
      
       Computation in decimal (for humans reading)
      
          12 / 10 = 1   
          12 % 10 = 2     
      
       (We write computations in human readable for in Java !)  
      

Algorith: converting a TWO-digits 2's compl repr to it's string repr
 

Steps of the conversion algorithm:

   input:     00001100         (twelfe)

   (1) Divide by 10 and mod by 10 to obtain
       the digits of the input:

       digit0 = input % 10    (digit0 = 00000010  = 2(10))
       digit1 = input / 10    (digit0 = 00000001  = 1(10))

   (2) Map each digit to its ASCII char

       char0 = digit0 + '0'   (char0 = '2')
       char1 = digit1 + '0'   (char1 = '1')

   (3) Concatenate ASCII chars to form the number string:

         char1 + char0 = "12"
   

Java program that shows how it's done

 int i;
 char[] c = new char[2]; // char array of size 1
                         // (because we only have 1 character)

 i = 12;        // This statement will assign the
                // 2's compl code 
                // 00000000000000000000000000001100 
		// to variable i

                // *** Change to any value between 0 and 99

 c[0] = (char) (i/10 + 48);  // 48 = '0'
 c[1] = (char) (i%10 + '0'); 

 /* ---------------------------------------------
    Make a string out of the character(s)
    ---------------------------------------------- */
 String s = new String(c); // Make a string using the characters
   

DEMO: /home/cs255001/demo/atoi/ConvInt2Digits.java
Experiment:   try i = 102