Value of the decimal number 12 is computed as: 1×101 + 2×100 = 1×10 + 2×1 |
Notice that if we perform the same computation with binary numbers, we will get the binary representation for the same number:
00000001×00001010 + 00000010×00000001 = 00001010 + 00000010 = 00001100 And: Binary number 00001100(2) is the decimal number 12(10) !!! |
We can use this high school formula and binary arithmetical operations to compute the 2's complement representation from it's string !
their binary ASCII code:
"12" consists of the ASCII code: 00110001 00110010 Map each ASCII code uisng "input - 48": 00110001 (=49) - 00110000 (=48) --> 00000001 (=1) 00110010 (=50) - 00110000 (=48) --> 00000010 (=2) |
After we got their computable 2's complement codes for the digits, we can use the high school formula to find the value:
1×10 + 2 The computer can perform this calculation in binary: 00000001×00001010 + 00000010 = 00001010 + 00000010 = 00001100 |
and obtain the 2's complement representation 00001100 for the String "12" !!!
// File: /home/cs255001/demo/atoi/Atoi_1.java // // Convert "12" to 2's complement // public class Atoi_1 { public static void main(String[] args) throws Exception { String s = "12"; // You can use any string of 2 digits int[] v = new int[2]; // To save values of the digits int i; System.out.println("ASCII codes (in decimal) = " + (int) s.charAt(0) + " " + (int) s.charAt(1) ); /* ------------------------------------------------------- Convert the ASCII character to 2's compl - per digit ------------------------------------------------------- */ v[0] = (int) s.charAt(0) - 48; v[1] = (int) s.charAt(1) - 48; i = v[0]*10 + v[1]; // High school formula to find value of dec number // Note: calculation performed in BINARY by computer !!! System.out.println("integer value i = " + i); /* ============================================================= Prive to students that this is an integer (you can add !) ============================================================= */ i = i + 1; System.out.println("After i+1, i = " + i); } } |
Sample output:
cheung@aruba> java Atoi_1 ASCII codes (in decimal) = 49 50 integer value i = 12 After i+1, i = 13 |
Notice that the string "12" is represented by the 2 ASCII codes 00110001 (= 49) 00110010 (= 50) as shown in the sample output.
When we subtract 48 from them, we get 1 and 2.
That's why the high school formula can be used to compute the 2's complement representation because 1 and 2 are suitabel for computation (while 49 and 50 are not !!)
How to run the program:
|