'How much value do the 8 bit variable holds?

Probably answer is 256 but I am not satisfied with it.

Suppose a variable has 8 bits , its mean its 8th bit can hold the value 256 . But it also has other seven bits . Wouldn't the total value be the sum of all bits?

To me final value that 8 bit variable holds would be the sum of all bits. But it doesn't. Why?



Solution 1:[1]

The max value 8 bits can hold is: 11111111 which is equal to 255. If you have a signed value, the max value it can hold is 127, the left-most bit is used for sign.

The binary 10000000 equals 128 (2 ^ 7), not 256. That's where your confusion lays I think.

00000001 = 2 ^ 0 = 1
00000010 = 2 ^ 1 = 2
00000100 = 2 ^ 2 = 4
00001000 = 2 ^ 3 = 8
00010000 = 2 ^ 4 = 16
00100000 = 2 ^ 5 = 32
01000000 = 2 ^ 6 = 64
10000000 = 2 ^ 7 = 128

Solution 2:[2]

The value is indeed the sum of all bits set to 1, but the place value of the eighth bit is 27 (128), not 256 as you suggest - the least significant bit is 20 (i.e. 1), so for eight bits the MSB is 27. You appear to have started from 21 (2) .

For an unsigned integer:

Bit 0 = 20 = 1
Bit 1 = 21 = 2
Bit 2 = 22 = 4
Bit 3 = 23 = 8
Bit 4 = 24 = 16
Bit 5 = 25 = 32
Bit 6 = 26 = 64
Bit 7 = 27 = 128

Sum of all ones = 255 - not 256 as you suggest: 0 to 255 = 28 (256) values.


For a two's complement signed 8 bit type:
Bit 7 = -27 = -128

Sum of all ones = -1,
while if Bit 8 = 0, sum = +127,
and all zeros except bit 8 = -128.
(-128 to +127 = 28 (256) values).


Either way an 8 bit integer signed or otherwise has 28 (256) possible bit patterns.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Clifford
Solution 2