Win a copy of OCP Java SE 8 Programmer II Exam Study Guide this week in the OCP forum!
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# Range of byte

Ranch Hand
Posts: 44
How the negative end of a byte is -128. Please explain

Sheriff
Posts: 23451
46
Because the potential values run from -128 to +127. So the low end of the range is -128. Please explain why you think this is a problem or a question.

Aruna Balasuriya
Ranch Hand
Posts: 44
I want to know how this -128 value get from.(How there is a difference between positive end and negative end)

author
Marshal
Posts: 23435
138

Aruna Balasuriya wrote:I want to know how this -128 value get from.(How there is a difference between positive end and negative end)

Java, along with practically every modern day processor, uses the twos complement format to store bytes. And yes, twos complement's range does that.

http://en.wikipedia.org/wiki/Two's_complement

Henry

lowercase baba
Bartender
Posts: 12613
50
numbers are represented by bit patterns. a bit can be '0' or '1'. Each bit added to the storage space doubles the total possible values.

So lets assume we only had one bit to store values. you could store two total. zero is usually one, and so that leaves one other value of -1.

Now assume we have 2 bits, which would allow us to store four values. Again, you need 0 to be one of them. so you could do (0,1,2,3), or (-1,0,1,2) or (-2,-1,0,1). This extrapolates to (-128, -127, -126...-2, -1, 0, 1,2,...126, 127) when you get up to 8 bits.

another way to think about it is that half the values that can be stored are negative, and half are NON-negative. one of those non-negative values is 0, meaning you have one-less spot to represent a positive number.

Paul Clapham
Sheriff
Posts: 23451
46
But Fred, that explanation doesn't exclude the possibility of (-127, 128) being the valid range for bytes.

 With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.