Constantine
Constantine

Reputation: 2032

Get value range for number of bits in Java

I need to calculate signed value range for some bits count.
For example:

bitscount = 4

min value = -2^3;

max value = 2^3 - 1; in bitwise it is (1<<3 - 1)

I forgot how to compose bitwise for min value. Please help.

Upvotes: 1

Views: 175

Answers (2)

Robin Kang
Robin Kang

Reputation: 21

Try like this:

int bits_count = 4;  // between 2 ~ 32 (I assumed int type is 32bits signed integer)
int min_value = -(1 << (bits_count - 1));
int max_value = (1 << (bits_count - 1)) - 1;

And reference site: http://www.tutorialspoint.com/java/java_bitwise_operators_examples.htm

Upvotes: 1

Ashwani
Ashwani

Reputation: 2052

minValue = -(1 << (bitscount - 1));
maxValue = (1 << (bitscount - 1)) - 1;

Upvotes: 1

Related Questions