Why from 0 to 255?

Share

In a computer, there are cases when a number may go from 0 to 255. That is, its minimum value is zero, and its maximum value os two hundred fifty five. It doesn't reach 256. For example, when typing RGB colors, RGBA, or IPv4 addresses, numbers go from 0 to 255.But why 255 exactly? Why not 100 or 1000? What is special about the number 255?

The number 255 is the maximum value that fits in a single byte. One byte has 8 bits of data. Each bit may only have two values: 0 or 1. With 2 bits, there are 4 possible combinations: 00, 01, 10, and 11. With 8 bits, there would be 256 different combinations, or 2 to the 8th power. We transform these combination to decimal numbers by interpreting them as binary numbers. Since there are 256 combinations of 8 bits, there are 256 different numbers that we can represent with 8 bits. One of these numbers is the zero (00000000), so we subtract this 1 number from the total of combinations to obtain the maximum value that one byte representing a non-negative integer number may have (11111111) which would be 255, ou 28 - 1.

Diagram showing how bits and binary numbers work using lamps turned on and off as analogy.
Source: br.virtualcuriosities.com. Illustration of lamp by Ignacio javier igjav. License: CC BY-SA 3.0.

Although this sounds complicated, this same formula works for the decimal numbers we normally use: the maximum value we can represent with 3 decimal digits is 999, or 103 - 1. Binary numbers are base 2, and decimal numbers are base 10. This base, to the power of how many digits we have, minus one, is always the maximum value we can have with that many digits.

XN - 1 = maximum value for N digits in base X

Numbers from 0 to 255 can also be represented by two hexadecimal digits. For example, a RGB color uses 1 byte for each color channel. That is, R goes from 0 to 255, G goes from 0 to 255, and B goes from 0 to 255. Given the RGB tuple 255-0-128, we could write it in the hexadecimal form FF-0-80. In the case of colors, it's common for this hexadecimal representation to start with a # (octothorpe), e.g. #ff0080.

In the case of integer numbers that may be negative, one bit of the byte would be used for the sign (negative or positive). Since the number zero is neither negative nor positive, one of the two sides would spend a combination to represent the zero, and the other side would have one number extra. For example, if 00000000 is the minimum negative value, and 10000000 represents zero, one byte may represent a value from -128 (0000000) to 127 (11111111).

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *