| Integers: Sign extension | ||||||||||||
| We may need to change the number of bits used to represent a number. | ||||||||||||
| For example, C has int, short int, and long int to represent integers. | ||||||||||||
| The language doesn't specify the exact size of each form, but | ||||||||||||
| sizeof (short int) <= sizeof (int) <= sizeof (long int) | ||||||||||||
| How do we cast from one kind of int to a larger number of bits? | ||||||||||||
| ints are represented in N-bit 2C | ||||||||||||
| To convert a number from N bits to N + K bits in 2C notation, | ||||||||||||
| copy (extend) the sign bit from bit N-1 to bit N + K -1 | ||||||||||||
| If the value is positive, all the higher-order bits will become 0; | ||||||||||||
| if the value is negative, all the higher-order bits will become 1. | ||||||||||||
| All of the other bits (location N-2, . . . , 0) remain unchanged. | ||||||||||||
| Example: | ||||||||||||
| 3ten is 0011 in 4 bits | ||||||||||||
| In 8 bits, it becomes 00000011 (the zero sign bit is extended to the left). | ||||||||||||
| -3ten is 1101 in 4 bits | ||||||||||||
| In 8 bits, it becomes 11111101 (the one sign bit is extended to the left). | ||||||||||||