lakhansoren
lakhansoren

Reputation: 172

Question related to range of the primitive datatypes

In java, short has range of -128 to 127. Why is it not -127 to 127 ? Considering one bit is used for storing the sign of the number, the negative limit should have been -127 which is sum of 2^6+2^5+2^4+2^3+2^2+2^1+2^0 ? What am I missing in my calculations ?

Upvotes: 0

Views: 67

Answers (3)

Alexander Kaschta
Alexander Kaschta

Reputation: 136

You are using 8-Bits to store that in the memory of the computer. This would simply 0 to 255. Considering that you also want negative numbers, you must change the way of looking on these numbers.

Let's say that we take the 8th bit as an indicator for negativity. The negative number would be the negation of the positive number. This would let us display numbers from -127 to 127, but there would be two ways to display the 0: 1111 1111 and 0000 0000. This is called One's Complement.

Because engineers wanted to use all the available space, the came up with a new idea. To convert a position number in to a negative ( * - 1) they decided to fully negate the number and increment it by one. This would give them the possibility of using the whole 256 range. That's the Two's Complement. There are 128 negative numbers + 1 Zero + 127 positive numbers, which makes 256 numbers.

Upvotes: 1

Joe C
Joe C

Reputation: 15704

I will assume you meant byte rather than short, as short has a range of -32768 to 32767.

You appear to be under the impression that, for integer types (including short), a negative number is represented with a signed bit and the rest of the number as normal. So -1 would be represented as 1000.0001 (dot added for readability). This, however, is incorrect.

In reality, -1 is represented as 1111.1111, and 1000.0000 is actually -128 (and not -0, which doesn't exist for this type). This is to keep the arithmetic consistent across all values.

Upvotes: 1

Adeel Malik
Adeel Malik

Reputation: 21

Your calculations are wrong. Total possibilities are 2^8 and that is equal to 256. From -128 to 127 because we count 0 as one of those numbers. 128+128 = 256. But 256 + '0' = 257. So it has to be from -128 to 127.

Upvotes: 0

Related Questions