Win a copy of OCP Java SE 8 Programmer II Exam Study Guide this week in the OCP forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Range of byte  RSS feed

 
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How the negative end of a byte is -128. Please explain
 
Sheriff
Posts: 23451
46
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!