import java.io.*; class ItoaDemo2 { /* ----- PutBit(b): prints "1" if b != 0 and "0" otherwise ----- */ private static void PutBit(int b) { if (b != 0) System.out.print("1"); else System.out.print("0"); } /* ----- PrintAsciiCode(c): prints an 8 bit quantity in legible "0" and "1" ----- */ private static void PrintAsciiCode(char c) { int i; for (i = 7; i >= 0; i--) PutBit(c & (1 << i)); } /* ----- PrintIntCode(c): prints a 32 bit quantity in legible "0" and "1" ----- */ private static void PrintIntCode(int k) { int i; for (i = 31; i >= 0; i--) PutBit(k & (1 << i)); } /* --- itoa(value): Integer to Ascii conversion function --- */ private static String itoa(int value) { int sign, i, j; String result; char next_char; System.out.print(" Input value = "); PrintIntCode(value); System.out.println(" (" + value + ")"); System.out.println(); /* ------- Handle trivial case... if (value == 0) return("0"); ------- */ /* ------- Check sign ------- */ if (value < 0) { sign = -1; value = -value; } else { sign = 1; } System.out.println(" sign = " + sign); System.out.println(); /* ------- Convert number part ------- */ System.out.println(" ** Converting number part:"); result = ""; System.out.print(" result = \"" + result + "\"\t\tvalue = "); PrintIntCode(value); System.out.println(" (" + value + ")\n\n"); while (value > 0) { next_char = (char) ('0' + (value % 10)) ; result = next_char + result; value = value / 10; System.out.print(" result = \"" + result + "\"\t\tvalue = "); PrintIntCode(value); System.out.println(" (" + value + ")"); System.out.print(" Actually, result = "); for (i = 0; i < result.length(); i++) { PrintAsciiCode(result.charAt(i)); System.out.print(" "); } System.out.println(" (after 1 iteration)\n"); } System.out.println(); /* ------- Put the sign in ------- */ System.out.println(" ** Put in sign:"); if (sign == -1) { result = "*******" + result ; } else { result = result + ""; } System.out.println(" result = \"" + result + "\""); System.out.print(" Actually, result = "); for (i = 0; i < result.length(); i++) { PrintAsciiCode(result.charAt(i)); System.out.print(" "); } System.out.println( " (ASCII codes !)\n"); return(result); } public static void main(String[] args) throws IOException { BufferedReader stdin = new BufferedReader (new InputStreamReader(System.in)); String s; int value; int i; System.out.println("Program reads an integer converts "+ "it to ASCII representation"); System.out.println(); while (true) { System.out.println(); System.out.print("Enter a number: "); value = Integer.parseInt (stdin.readLine()); System.out.print("The internal representation for "+value+ " is: "); PrintIntCode(value); System.out.println(); System.out.println(); System.out.print("Now converting 2's complement "+ "representation to ASCII..\n"); s = itoa(value); System.out.println(); System.out.println("Output: s = " + s); } } }