Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (9.5k points)

When I calculate byte - 8bits like this 2^7+ 2^6 +2^5 + 2^4 + 2^3 + 2^2 + 2^1 +  2^0. It added up to 255. Then how the byte range is -128 to 127? 

Can anyone tell me how to calculate the range of primitive data types in Java? 

 

2 Answers

0 votes
by (19.7k points)

-2^(n-1) to (2^(n-1)-1) is the formula to calculate the range of data types. 

Where n = no.of.bits of the primitive data type. 

For example: for the byte data type, n = 8 bits

-2^(8-1) to (2^(8-1)-1)

The above calculation will give you -128 to 127. Now, coming to the question of why it’s not 255. The reason is a byte, int, short, double are signed data types meaning it has half the range below 0 (negative) and half the range above 0 (positive). The first bit represents a sign (+ or -). The remaining bits are 7. That’s why 2^(8-1) = 128. We take 0 as a positive sign, so the range is 2^(8-1) - 1 for positive numbers. 

If you want to learn more about Javathen go through this Java tutorial by Intellipaat for more insights.

0 votes
by (2.7k points)

For a primitive data type, to find the range of values, we use the following formula:

-2^(n-1) to (2^(n-1) - 1)

where n is the number of bits for the data type.

For example, using the byte data type, which has 8 bits, so n = 8, we get:

-2^(8-1) to (2^(8-1) - 1)

This gives the range of -128 to 127. You would be thinking why it's not 0 to 255 because, obviously, 8 bits can represent 256 different values. The reason is that byte (like int, short, and double) is a signed data type. Signed data types use one bit to represent the sign; the rest 7 bits are used to represent the value.

This gives us 2^7 = 128 values that lie below zero (negative), and 128 above zero (positive), but in the positive range as zero is included. The sum thus gives a positive range up to 2^(8-1) - 1, or 127.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

31k questions

32.9k answers

507 comments

693 users

...