Each Java data type for representing integers is signed: left most bit 0 means positive, left most bit 1 means negative. The following table describes the integer data types:
|
Primitive data type |
Memory allocation |
Min / Max value |
|
byte |
1 byte |
-128 / 127 |
|
short |
2 bytes |
-32,768 / 32,767 |
|
int |
4 bytes |
-2,147,483,648 / 2,147,483,647 |
|
long |
8 bytes |
-9,223,372,036,854,775,808 / 9,223,372,036,854,775,807 |
Two's complement is the standard convention used to represent signed binary integer data types in many programming languages including Java. This avoids having +0 and -0 values, which could complicate hardware requirements. To represent a number in two's complement first the word size must be determined so the position of the left most bit is known, next note that all positive numbers have a 0 as the left most bit. Inverting all bits in the positive number and adding 1 derives a negative number. To read a negative number reapply the same algorithm to get the positive value and insert the negative sign. A shortcut for applying two's complement: copy all the bits from the least significant (rightmost) bit up to and including the first 1, then invert the rest. See Complements in Radix r for information on how to apply this technique for radix other than 2. Consider the table below which shows the binary representation of Java byte data type (spaces added to binary numbers to improve readability):
| Java Byte Data Type | ||||
|---|---|---|---|---|
|
Decimal |
8 bit Binary |
invert |
add 1 for |
Decimal |
|
0 |
0000 0000 |
- |
- |
- |
|
+1 |
0000 0001 |
1111 1110 |
1111 1111 |
-1 |
|
+2 |
0000 0010 |
1111 1101 |
1111 1110 |
-2 |
|
+3 |
0000 0011 |
1111 1100 |
1111 1101 |
-3 |
|
+4 |
0000 0100 |
1111 1011 |
1111 1100 |
-4 |
|
+5 |
0000 0101 |
1111 1010 |
1111 1011 |
-5 |
|
¯ |
|
|
|
¯ |
|
124 |
0111 1100 |
1000 0011 |
1000 0100 |
-124 |
|
125 |
0111 1101 |
1000 0010 |
1000 0011 |
-125 |
|
126 |
0111 1110 |
1000 0001 |
1000 0010 |
-126 |
|
127 |
0111 1111 |
1000 0000 |
1000 0001 |
-127 |
|
- |
- |
- |
1000 0000 |
-128 |
| Complements in Radix r | Euclid's Division Algorithm | Base Conversion | Java Primitive Data Types: | Reals | Number Systems | Homework |