Big Moose Saloon
 Search | Java FAQ | Recent Topics Register / Login Win a copy of The Mikado Method this week in the Agile and other Processes forum!

# Formula for primitive type sizes

Pal Sudarshan
Ranch Hand

Joined: Jun 10, 2004
Posts: 52
Hi All,

Question: how does the computer represent -128 for byte data type in memory?

My question arises from the fact that most computers nowadays use 2's complement to store integral data types.

Now the algorithm to represent a negative number in computer is:
1. Discard the sign of the negative number, make it positive
2. Invert all the bits; this is the one's complement
3. Add 1 to the one's complement

But how can we represent 128, when the possible positive value for byte data type go up to only 127. So how does the computer store -128 in memory for the byte data type. Thanks.
Jessica Sant
Sheriff

Joined: Oct 17, 2001
Posts: 4313

very simply, it doesn't. As you said, a byte can only go from -128 to 127 inclusive.

If you need to store the number 128, you need to use a short (whose range is -32768 to 32767, inclusive).

Try it out. Create a simple for loop and print out the results -- what happens when you reach 128??

- Jess
Blog:KnitClimbJava | Twitter: jsant | Ravelry: wingedsheep
Pal Sudarshan
Ranch Hand

Joined: Jun 10, 2004
Posts: 52
I wasn't clear with my question.

How does the computer store -128 in memory?
Anil Hulikal
Greenhorn

Joined: Apr 02, 2004
Posts: 29
1 byte = 8 bits

The relationship between the number of bits and how many binary values can be had using them is

87654321

2^82^72^62^52^42^32^22^1

What this means is, using 1 bit you can have 2^1 = 2 values. In other words, if there was only one bit to represent your data, you can only have one of the two values: Either a one, or a zero. If you had two bits, you would have 2^2 = 4 possible combinations to represent the data, and those would be: 00, 01, 10, 11 (0,1,2 and 3 in decimal). Likewise, using 8 bits you would have 2 ^ 8 possible combinations 00000000 through 11111111 (0 through 255 decimal). Now, if you were to represent negative numbers also using the same number of bits how would you do it? It's easy. Use the MSB (most significant bit, or the left most bit) as a sign bit. If we did that, we are left with 2^7 (128) possible combinations, and that includes a zero. So, now, based on the value of MSB, you identify whether it is a positive number or a negative one

MSB Lower bitsDecimal
0 0000000 0
01111111127
10000000-128
11111111-1

In general, we can say that with "n" number of bits, the integer values range from [-2^(n-1)] to [(2^(n-1)) - 1]
[ June 28, 2004: Message edited by: Anil Hulikal ]

Just stay focused.
Pal Sudarshan
Ranch Hand

Joined: Jun 10, 2004
Posts: 52
Thank you both.

I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week

subject: Formula for primitive type sizes