import java.io.*; class Itoa { /* --- myToString(): Integer to Ascii conversion function --- */ public static String myToString(int input) { boolean inputWasNeg; int remainder[] = new int[100]; char digit[] = new char[100]; // Max 100 digits in number String result; int nDigits; /* --------------------------------------- Check if input is negative --------------------------------------- */ if (input < 0) { inputWasNeg = true; input = -input; // Negate to make input positive } else { inputWasNeg = false; } /* ------------------------------------------------------- Get all digit by collecting remainders divided by 10 ------------------------------------------------------- */ nDigits = 0; // Count # digits in number while (input > 0) { remainder[nDigits] = input % 10; nDigits++; input = input / 10; } /* --------------------------------------------------------- Convert "digits" to character (ASCII code) using: ASCII code = digit + 48 --------------------------------------------------------- */ for (int i = 0; i < nDigits; i++) { digit[i] = (char) (remainder[i] + 48); // Or use '0' for 48 } /* --------------------------------------------------------- Make a string (start with last remainder) --------------------------------------------------------- */ result = ""; // Initialize output string for (int i = nDigits-1; i >= 0; i--) result = result + digit[i]; // Add next digit /* --------------------------------------------------------- Prepend '-' if input was negative --------------------------------------------------------- */ if ( inputWasNeg == true ) { result = "-" + result ; // Try: "******" + result for banks } else { result = result; // Does nothing... } return(result); // Returns a String of ASCII codes // for the numeric string that represents // the integer input encoded in the BINARY // number in parameter variable input } public static void main(String[] args) throws IOException { int x; String s; x = -123; // Stores 2's compl binary number in x !!! System.out.println("x = " + x); /* ------------------------------------------------- Prove to students that x is an integer (can add) -------------------------------------------------- */ x = x + 10000; System.out.println("x + 100000 = " + x); System.out.println("================================"); x = -123; s = myToString(x); // Converts 2's compl code into a String System.out.println("String representation = " + s ); /* --------------------------------------------- Prove to students that s is a string ---------------------------------------------- */ s = s + 10000; System.out.println("s + 10000 = " + s); } }