|
Input Output 2's complement (int) code ASCII character code --------------------------- ------------------------------------- 00000000 (zero) --> 00110000(2) = 48(10) (character '0') 00000001 (one) --> 00110001(2) = 49(10) (character '1') 00000010 (two) --> 00110010(2) = 50(10) (character '2') 00000011 (three) --> 00110011(2) = 51(10) (character '3') 00000100 (four) --> 00110100(2) = 52(10) (character '4') 00000101 (five) --> 00110101(2) = 53(10) (character '5') 00000110 (six) --> 00110110(2) = 54(10) (character '6') 00000111 (seven) --> 00110111(2) = 55(10) (character '7') 00001000 (eight) --> 00111000(2) = 56(10) (character '8') 00001001 (nine) --> 00111001(2) = 57(10) (character '9') |
The output of the conversion can be accomplished by the following mapping operation (because the ASCII codes are consecutive):
ASCII code = 2's complement code + 48 |
// File: /home/cs255001/demo/atoi/JavaOutput_2.java // // Converting a binary number between 0 and 9 to a String // public class JavaOutput_2 { public static void main(String[] args) throws Exception { int i; char[] c = new char[1]; // char array of size 1 // (because we only have 1 character) i = 4; // *** Change to any value between 0 and 9 c[0] = (char) (i + 48); // c is equal to ASCII code for the number ! /* --------------------------------------------- Make a string out of the character(s) ---------------------------------------------- */ String s = new String(c); System.out.println(">>> " + s); /* --------------------------------------------- Prove to students that s is a string ---------------------------------------------- */ s = s + " - hello, this is a string !"; System.out.println(">>> " + s); } } |
How to run the program:
|
You can change the statement i = 4; to any value between 0 and 9.
|
Answer:
|