Recall that computers use the 2's complement code to represent (signed) integer (number) values for computation purpose:
value Repr in 8 bits Repr in 16 bits --------+----------------------------+-------- ... ... .... -3 11111101 1111111111111101 -2 11111110 1111111111111110 -1 11111111 1111111111111111 0 00000000 0000000000000000 1 00000001 0000000000000001 2 00000010 0000000000000010 3 00000011 0000000000000011 ... ... .... |
Signed integer (whole) value must be stored in 2s complement code in order to perform arithmetic operations on the numeric value !!
Recall also that the key board that humans use to input (= enter) numbers as a series of ASCII codes
Examples:
Number entered: Data received as input by program: ------------------+---------------------- "1" 00110001 "15" 00110001 00110101 "-15" 00101101 00110001 00110101 |
Note: ASCII code and 2s complement code are different codes !
When you type the number 15 on the keyboard, the computer system will store the following 2 ASCII codes in memory:
In contrast: recall that the byte value for 15 is represented by the 00001111 (in 8 bits) !!
Difference between a string representation of integer numbers and their 32 bits 2s complement code (representation):
Number entered: Data received as input by program: ------------------+---------------------- "1" 00110001 "15" 00110001 00110101 "-15" 00101101 00110001 00110101 Number entered: What is needed to perform calculations: ------------------+---------------------- "1" 00000000 00000000 00000000 00000001 "15" 00000000 00000000 00000000 00001111 "-15" 11111111 11111111 11111111 11110001 (I broke up the 32 bits 2 compl code into groups of 8 bits) |
Remember: we must respresent integers in 2s complement code in order to perform calculations !!
Solution:
|
The Java class Integer in Java's library has provided these conversion methods:
int parseInt( String s ): return the int value converted from the input string s String toString( int x ): return a String that represents the integer (whole) value x |
|