Apply what you have learned to write the Java statements that assign 5 to a variable named plusFive with a byte data type and –5 to a variable named minusFive, also a byte data type. These are the required statements: byte plusFive = 5 byte minusFive = –5 It is the nature of a higher-level programming lan- guage that you do not need to know what is hap- pening at the machine-code level. Nevertheless, it is good to understand the storage formats of data. Stor- ing positive numbers as binary numbers is straight- forward. Negative numbers are a different story. CPU designers most often employ a scheme called Two’s Complement to represent both posi- tive and negative integers. The leftmost bit is re- served for a sign: 0 means the number is positive, 1 means the number is negative. This is called the sign bit. The remaining bits are used for the value, as shown. One notable impact is that because the leftmost bit cannot be used as a value, the number of bits that can be used for the value is reduced. In a byte, for example, instead of having all eight bits available to represent the binary value, there are only seven bits available for the data value. The largest binary number that fits in seven bits is 127. 0 1 1 1 1 1 1 1 The Two’s Complement scheme is not obvi- ous, but it is simple, and it works! First, write the positive number. Second, flip each of the bits in that number. If the bit is a 1, make it a 0. If the bit is a 0, make it a 1. Last, add 1 to the rightmost bit. Do not forget to carry if a 1 is already in the rightmost bit. This binary addition table can be used for your work. + 0 1 0 0 1 1 1 10 To use this table, find the number at the inter- section of the two numbers you are adding. For example, 0 + 1 = 1 and 1 + 1 = 10. Example 1 Show the binary representations of the two vari- ables defined above. plusFive 0 0 0 0 0 1 0 1 First, write the positive number. 0000 0101 Second, flip the bits. 1111 1010 Third, add 1 to the rightmost bit. 1111 1011 minusFive 1 1 1 1 1 0 1 1 If the Two’s Complement scheme worked, the sum of 5 and –5 will be 0. Add the two binary numbers to verify that the sum is 0. 0000 0101 + 1111 1011 1 0000 0000 Math and Java Two’s Complement (continued) 78 Introduction to Computer Science: Java Programming Copyright Goodheart-Willcox Co., Inc.
Previous Page Next Page