Range of numbers in a byte
We know that a number gets stored in 8 bits, as a programmer you might also know that numbers range from (-128 to 127) in 1 byte. But 2^8 = 256 isn't it? So why? How do the negative numbers come into the picture and why it's not (-256 to 256) or not (-128 to 128)?
How are the numbers arranged into a byte?
Numbers are arranged into a box of 8 bits, You can imagine a table with 8 rows, now the 0s and 1s will be placed there accordingly, but have you ever thought about how the negative numbers are arranged?
The leftmost row is for the sign, 0 means + and 1 means -. See the image below for a better understanding.
Why "-128 to 127"?
By the above paragraph, you can conclude that numbers(0s and 1s ) get placed in only 7 bits or boxes, So, 2^7=128, and the remained bit is for the sign, so it comes out -128 to 128 right?
Its range becomes 257 if we calculate from -128 to 128, but a byte can take up to 256(2^8) right? Because 0 is a number too, So it becomes -128 to 127, You can store 256 unique numbers only.
Why not "-127 to 128"?
You might think "why not -127 to 128?" Cheating right? It's not.
0 is taken from the positive side because 0 is a positive number. (-) negative of 0 is 0 in binary, How?
You have to convert 0 into a negative binary first, take 2's compliment of 0 it becomes 100000000, you can notice it's 9 bits, and the extra bit will be discarded as a byte can only take up to 8 bits.
So, you can see -0 is 0 itself.
Numbers range from (0 to 127 = 128) +( -1 to -128 = 128) = 256 unique numbers.
FORMULA for Range = -2^(n-1) to 2^(n-1) -1 .
Summary
You can store 256 unique numbers in a bit.
The first bit or MSB is reserved for the sign of the number.
If MSB is 0 it's a +ve number, if 1 it's a -ve number.
-0 = 0 in binary.
A bit can consist of -128 to 127 numbers including 0.
FORMULA for Range = -2^(n-1) to 2^(n-1) -1 .
Watch the video for a detailed discussion.
Subscribe to my newsletter
Read articles from Quazi Shams Kabir directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by