MOHIT SINGHANIA
MOHIT SINGHANIA

Reputation: 19

How limit of byte datatype in java is -128 to 127?

I have a doubt that byte datatype has 1 byte memory which means 8 bits, in it and 1 bit is reserved as sign bit that leaves 7 bits for numeric values.

So 7 bits can have highest value

26+25+24+23+22+21+20 = 127

so how come the limit for byte datatype is -128 to 127?

Upvotes: 2

Views: 611

Answers (3)

Karup
Karup

Reputation: 2079

You need to read about 2's complement notation.
The 2’s representation is a variation on 1's complement which does not have 2 representations for 0.
This makes the hardware that does arithmetic (addition, really) faster than for the other representations.
A 3-bit example

bit pattern: 100 101 110 111 000 001 010 011
1's comp:     -3  -2  -1   0   0   1   2   3
2's comp:     -4  -3  -2  -1   0   1   2   3

The negative values are all slid down by one, eliminating the extra zero representation.

Upvotes: 4

smoggers
smoggers

Reputation: 3192

Yeah you've answered your own question, if you can have 7 bits for numeric representation that means you can have 128 possible numbers. So 0-127 is a total of 128 values, but then you can use that other bit for 128 negative values. As 0 is already accounted for in the positive values (0-127), this allows for 128 negative values hence total range is -128 to +127.

Upvotes: 3

Glorfindel
Glorfindel

Reputation: 22651

You have 8 bits, so 28 = 256 possibilities. Between -128 and 127 (inclusive), there are exactly 256 integer numbers.

In your calculation, you're counting 0 twice, once as +0000000 and once as -0000000.

Upvotes: 4

Related Questions