There is a mapping between the input 2s complement code to its corresponding number string:
2's complement representation (32 bits) String representation ---------------------------------- ---------------------- 00000000000000000000000000000000 "0" 00000000000000000000000000000001 "1" 00000000000000000000000000000010 "2" 00000000000000000000000000000011 "3" ... ... 11111111111111111111111111111111 "-1" 11111111111111111111111111111110 "-2" 11111111111111111111111111111101 "-3" ... ... |
The toString( ) method implements this mapping !!!
public static String toString( int x ) { if ( x == 0 ) // Compares x with 00000000000000000000000000000000 return "0"; // Returns the ASCII codes for string "0" ! else if ( x == 1 ) // Compares x with 00000000000000000000000000000001 return "1"; // Returns the ASCII codes for string "1" ! else if ( x == 2 ) // Compares x with 00000000000000000000000000000010 return "2"; ... else if ( x == 10 )// Compares x with 00000000000000000000000000001010 return "10"; // Returns the ASCII codes for string "10" ! else if ( x == 11 )// Compares x with 00000000000000000000000000001011 return "11"; ... else if ( x == -1 )// Compares x with 11111111111111111111111111111111 return "-1"; else if ( x == -2 )// Compares x with 11111111111111111111111111111110 return "-2"; ... } |
Remember that the compiler will translate the characters into a ASCII code representation !!!
|
Now that we know what toString( ) must do, let's develop the algorithm in a piece meal fashion
I must remind you that we write expressions in decimal:
x = x % 10; x = x / 10; |
the computer program will perform the operations in binary:
x = x (in bin) % 00000000000000000000000000001010; x = x (in bin) / 00000000000000000000000000001010; |
because the compiler will translate the expression into 2s complement code !!!