From high school:
Value of the decimal number 12 is computed as: 1×101 + 2×100 = 1×10 + 2×1 (in decimal arithmetic) |
Remember that:
|
We write arithmetic operations in base 10 arithmetic in programs:
x = 1×10 + 2×1; // = 12
|
The compiler will translate and instruct the computer to perform the arithmetic operations in 2s complement arithmetic:
1 × 10 + 2 × 1;
| | | | (compiler !)
V V V V
x = 00000001×00001010 + 00000010×00000001
= 00001010 + 00000010
= 00001100 (= 12(10))
Note:
I used 8 bits in example.
In reality, the computer will use 32 bits
(because int typed data is 32 bits).
|
Example:
|
Step 1: map each digit to its 2s complement code
"12" consists of the ASCII code: 00110001 00110010 Map each ASCII code uisng "char - 48": 00110001 (=49) - 00110000 (=48) --> 00000001 (=1) 00110010 (=50) - 00110000 (=48) --> 00000010 (=2) |
Example:
|
Step 2: compute the value (with binary arithmetic
00000001×00001010 + 00000010×00000001 = 00001010 + 00000010 = 00001100 (I did the arithmetic in 8 bits, the computer program will use 32 bits) |
Implementing the conversion algorithm in Java:
String s = input string; // Need to use string of 2 digits int[] v = new int[2]; // Variable used to save values of the digits int x; // Convert each ASCII character to 2's compl v[0] = s.charAt(0) - '0'; v[1] = s.charAt(1) - 48; // It's the same ! // Find the 2s compl code using (binary) arithmetic x = v[0]*10 + v[1]; // Note: calculation will be // performed in BINARY by computer ! |
Remember:
we write
expressions in
decimal,
compiler will
translate into
binary
DEMO:
/home/cs255001/demo/atoi/ConvStr2Digits.java
Quiz:
|