The general algorithm to convert an int (2s compl) repr to a number string
 

Explained using input number -123:

 

The general algorithm to convert an int (2s compl) repr to a number string

   Input:  x = 11111111111111111111111111110100 (= -12(10))  

  (1) if ( x < 0 )
         sign = -1; x = -x; 
      else
         sign = 0;

           sign = -1, x = 00000000000000000000000000001100 

  (2) while ( x != 0 )
      { Divide the input repeatedly by 10 (in binary arithmetic)
        Prepend remainder of division to output
      }

       00001100 / 00001010:  Quotient = 00000001  Rem = 00000010
       00000001 / 00001010:  Quotient = 00000000  Rem = 00000001

   (3) Map each remainder to the corresponding ASCII code with:

           ASCII code = digit + 48

       We get the ASCII codes:   50 ('2')   49 ('1')

   (4) Concatenate the ASCII codes into a string
       starting from the last remainder to the first remainder

   (5) if ( sign == -1 ) 
          prepend output with "-"

Algorithm to convert a 2s compl representation into integer number string

The conversion algorithm in Java:

DEMO: /home/cs255001/demo/atoi/Itoa.java

Application: the System.out.println( ) method in Java

  • Methods in Java are overloaded:

       System.out.println("123"):  calls println( String s )  
       System.out.println(123):    calls println( int i )
      

  • The System.out.println( String s ) method is very easy:

      • System.out.println( String s ) sends the ASCII codes in input string s to the terminal

  • The System.out.println( int i ) method is more complex:

      1. System.out.println( int i ) first converts the 2s complement representation in input parameter i into a String representation

      2. It then send the ASCII codes of conversion string to the terminal