Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate the range of primitive data types?

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.

like image 251
Ankit Avatar asked Jun 07 '13 11:06

Ankit


People also ask

What is range in primitive data types?

The byte data type is an example of primitive data type. It isan 8-bit signed two's complement integer. Its value-range lies between -128 to 127 (inclusive). Its minimum value is -128 and maximum value is 127.

How do you find the range in Java?

Range = Max – Min. Coefficient of Range = (Max – Min) / (Max + Min)

Which primitive type has a size range of to 127?

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).


2 Answers

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
like image 132
Jayani Sumudini Avatar answered Sep 17 '22 02:09

Jayani Sumudini


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)

like image 35
LuigiEdlCarno Avatar answered Sep 18 '22 02:09

LuigiEdlCarno