The decimal number 12 has 2 digits:
1 and 2
How can you get the digits 1 and 2 from 12 ?
Answer:
The digit 1 can be obtained from 12 by the computation: 12/10 = 1
The digit 2 can be obtained from 12 by the computation: 12%10 = 2
|
Once we obtain the individual digit, we can use the mapping:
ASCII code = 2's complement code + 48 |
to obtain their ASCII codes 00110001 (= 49) 00110010 (= 50).
The string "12" can then by found by concatenating the ASCII codes !!!
their binary ASCII code:
// File: /home/cs255001/demo/atoi/JavaOutput_3.java
//
// Converting a binary number between 0 and 99 to a String
//
public class JavaOutput_3
{
public static void main(String[] args) throws Exception
{
int i;
char[] c = new char[2]; // char array of size 1
// (because we only have 1 character)
i = 12; // This statement will assign the
// 2's compl code 00001100 to variable i
// It actually uses 32 bits, but I list
// the last 8 bits for brevity.
// *** Change to any value between 0 and 99
c[0] = (char) (i/10 + 48); // c[0] is the left most digit in number i
c[1] = (char) (i%10 + 48); // c[1] is the right most digit in number i
/* ---------------------------------------------
Make a string out of the character(s)
---------------------------------------------- */
String s = new String(c); // Make a string using the characters
System.out.println(">>> " + s);
/* ---------------------------------------------
Prove to students that s is a string
---------------------------------------------- */
s = s + " - hello, this is a string !";
System.out.println(">>> " + s);
}
}
|
Sample output:
cheung@aruba> java JavaOutput_3 >>> 12 >>> 12 - hello, this is a string ! |
How to run the program:
|
|
Answer:
|
The reason is similar to the previous quiz; the character in c[0] is the : character because the ASCII code 58 represents :