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.
The relationship between the number of bits and how many binary values can be had using them is
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