How to calculate the range of primitive data types?

17,315

Solution 1

Let's calculate range for 1 Byte

  1. 1 bit can take 0 or 1
  2. 1 Byte = 8 Bits
  3. The first bit is used as a sign ( - or + )
  4. then remaining bits are 7
  5. so we can write 2^7 = 128 different numbers for one sign
  6. we get 0 as a positive sign. then we have 128 numbers for the negative side,127 numbers for the positive side and 0 (zero)
  7. so the range is -128 to 127 including 0

Solution 2

It is a signed type, meaning, it still has a range of 255 (as you have correctly calculated), but it starts at -128. So half the range is below zero, 1 possible number is = (zero) and the remaining 127 are above 0.

The first bit is the sign. (1 - minus, 0 - plus)

Solution 3

That's because the first bit is used for the sign, since the data type is signed.

Please refer to http://en.wikipedia.org/wiki/Signed_number_representations

Since there is no unsigned primitive types in Java (like C or C#), is usual to cast it to a bigger type if you need to "overflow" the boundaries.

Solution 4

The last bit i.e. number 8 we are writing it 2^7 is a sign bit that decides negative or positive sign so it is 2^0 +2^1 +2^2 +2^3 +2^4 +2^5+ 2^6

Solution 5

Formula to calculate range in Java
-2(n-1) to +2(n-1)-1
Where n is the number of bit (1 byte= 8 bit)

So, for byte type range would be: -2(8-1) to +2(8-1)-1
or, -2(7) to +2(7)-1
or, -128 to +127

Share:
17,315
Ankit
Author by

Ankit

Updated on June 14, 2022

Comments

  • Ankit
    Ankit almost 2 years

    According to docs.oracle.com:-

    byte: The byte data type is an 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive). The byte data type can be useful for saving memory in large arrays, where the memory savings actually matters. They can also be used in place of int where their limits help to clarify your code; the fact that a variable's range is limited can serve as a form of documentation.

    Byte - 8 bits
    2^7 2^6 2^5 2^4 2^3 2^2 2^1 2^0

    128 64 32 16 8 4 2 1)

    Adding all these numbers we get a total of 255. Then how's the range which is -128 to 127 calculated. Is it hard-coded somewhere or there's some more technicality to this range?

    Any suggestions would be appreciated.

  • Ganesh Babu
    Ganesh Babu almost 4 years
    Good explanation