programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering OS Languages Paradigms IDEs Build Tools Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# Numeric range for given bit size

Ranch Hand
Posts: 30
How would I determine the range of numbers that can be used based on the bit size?

Ranch Hand
Posts: 479
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.

author
Sheriff
Posts: 23295
125

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

Mark Captain
Ranch Hand
Posts: 30
Thanks guys!

Java Cowboy
Sheriff
Posts: 16060
88
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.

Marshal
Posts: 56610
172
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.

Bartender
Posts: 6109
6
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
Posts: 23295
125
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

 It is sorta covered in the JavaRanch Style Guide.