DEV Community

Discussion on: Trivia: Why 255?

Collapse
lawrencejohnson profile image
Lawrence • Edited on

It's not that complicated if you are familiar with binary or hex. Even though the final number is 255, it includes 0, or 256 which is, you guessed it, 28. If you want to know why you see 8 bits so often, well, it depends on the case, but it's usually due to hardware or software limitations at the time. Hint: there are 8 bits in a byte.

And fwiw, that 16,77.216 number is a bit odd. It's 16777216 possible colors for our 24-bit palette (32 if you factor in transparency).

One final factor I'll add is not so much around the 0-255 number specifically, but generally the more reusable numbers we see are based around both binary and hexadecimal (or really just hexadecimal since all multitudes of that translate to binary). So, you see a lot of things like 161 which equals 24. But why? Well, hexadecimal mainly exists because it's a lot easier for humans to read than binary. IE:

0100 = 4
1101 = D

So, you see a lot of multitudes of 16.

161 = 24 = 16 = 0-15
162 = 28 = 256 = 0-255
163 = 212 = 4096 = 0-4095
and so on.

0-255 happens to fit neatly into two hexadecimal numbers, and there you have your rgb and hex color options for web.

Another place you might see things like 255 or 127 are in older database table declarations like varchar(255). This helped optimize storage and memory allocation in the past by getting the maximum amount of data without crossing into the next bit as the 256th value was reserved for NULL (or maybe it was a delimiter of sorts, I honestly forget it was so long ago). You can still find it in modern SQL too just as sort of a remnant of older programming styles, but not a lot of people really knew.

Collapse
kaos profile image
Kai Oswald

There's always someone who does the math 😁

Collapse
adam_cyclones profile image
Adam Crockett Author • Edited on

Indeed, I am glad too, I did say that it probably wasn't correct. I was on my phone on a train so no time for math, plenty of time for copy paste.

Collapse
adam_cyclones profile image
Adam Crockett Author

Good developers never take information at face value, nice call out.