| Author |
Numeric range for given bit size
|
Mark Captain
Ranch Hand
Joined: Nov 01, 2011
Posts: 30
|
|
How would I determine the range of numbers that can be used based on the bit size?
|
 |
Ralph Cook
Ranch Hand
Joined: May 29, 2005
Posts: 468
|
|
If by "bit size" you mean "the number of bits in the representation", a signed integer of N bits can represent from
- 2**(N-1)
to
2**(N-1) - 1
so an 8-bit signed integer can represent from -128 to 127
Java doesn't have unsigned integers; I assume you aren't asking about those.
The answer for floating-point numbers is somewhat more complicated, and in fact I use them so rarely I don't remember them off hand. The ranges themselves are available on many web sites; the calculation of them is a little harder to find.
|
 |
Henry Wong
author
Sheriff
Joined: Sep 28, 2004
Posts: 14613
|
|
Also, the wrapper classes has MIN_VALUE and MAX_VALUE constants which can give you the ranges. The exception are the Float and Double classes, where the range goes from negative MAX_VALUE to MAX_VALUE.
Henry
|
Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
|
 |
Mark Captain
Ranch Hand
Joined: Nov 01, 2011
Posts: 30
|
|
|
Thanks guys!
|
 |
Jesper de Jong
Java Cowboy
Bartender
Joined: Aug 16, 2005
Posts: 11642
|
|
|
If you are interested about why the range is what it is, then read about two's complement - that's the format in which computers store integer numbers.
|
Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 26720
|
|
Those figures refer to two’s complement; there are other representations, eg unsigned, excess 128 (for 8 bits) which have a range spanning 2 to the n where n is the number of bits available. Although the maxima and minima are different, the ranges are exactly the same as two’s complement.
Range = maximum value - minimum value + 1. It is easy to forget the + 1.
There is also sign and magnitude which has a range one smaller than that, because it includes 0 and -0.
I have only ever seen two’s complement and unsigned integers used.
Floating-point representations are completely different; Google for IEEE754 for the details, which are not at all easy to understand.
|
 |
Jeff Verdegan
Bartender
Joined: Jan 03, 2004
Posts: 3144
|
|
Ralph Cook wrote:If by "bit size" you mean "the number of bits in the representation", a signed integer of N bits can represent from
Java doesn't have unsigned integers; I assume you aren't asking about those.
char is unsigned, so its range it 0..2^16.
|
 |
Henry Wong
author
Sheriff
Joined: Sep 28, 2004
Posts: 14613
|
|
Oops, I forgot that floats and double supports Infinity. So, MAX_VALUE is the largest positive value, that is *not* infinity. And MIN_VALUE is the smallest positive value, that is *not* positive zero.
Henry
|
 |
 |
|
|
subject: Numeric range for given bit size
|
|
|