|
Illustrative example:
|
Steps of the conversion algorithm:
input: 00001100 (twelfe)
(1) Divide by 10 and mod by 10 to obtain
the digits of the input:
digit0 = input % 10 (digit0 = 00000010 = 2(10))
digit1 = input / 10 (digit0 = 00000001 = 1(10))
(2) Map each digit to its ASCII char
char0 = digit0 + '0' (char0 = '2')
char1 = digit1 + '0' (char1 = '1')
(3) Concatenate ASCII chars to form the number string:
char1 + char0 = "12"
|
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
// 00000000000000000000000000001100
// to variable i
// *** Change to any value between 0 and 99
c[0] = (char) (i/10 + 48); // 48 = '0'
c[1] = (char) (i%10 + '0');
/* ---------------------------------------------
Make a string out of the character(s)
---------------------------------------------- */
String s = new String(c); // Make a string using the characters
|
DEMO:
/home/cs255001/demo/atoi/ConvInt2Digits.java
Experiment:
try i = 102