简体   繁体   中英

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

2 6 +2 5 +2 4 +2 3 +2 2 +2 1 +2 0 = 127

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

You have 8 bits, so 2 8 = 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 .

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM