Hexadecimal

Term side of the Card.
Topic: Number Systems
Unit title: Hexadecimal
Categories: Concept, Format
Explanation side of the Card

Explanation: The base-16 number system that includes digits 0-9 and letters A-F, where A-F represent the values 10 to 15. It's commonly used in computing as a shorthand for binary values, as every two hexadecimal digits represent one byte of data.

Example

Wrongjs
const toHex = (r, g, b) =>
  '#' + [r, g, b].map((n) => n.toString(16)).join('');
toHex(255, 0, 8); // '#ff08'
Rightjs
const toHex = (r, g, b) =>
  '#' + [r, g, b].map((n) => n.toString(16).padStart(2, '0')).join('');
toHex(255, 0, 8); // '#ff0008'

Padding each channel to two hex digits keeps the color six characters long.

Common mistakes

  • Converting RGB to hex without padding, so 8 becomes '8' instead of '08' and the color is broken.

Key points

  • Each byte converted to hex is padded to two digits with padStart(2, '0').
  • Hex strings are parsed with parseInt(str, 16); Number(str) needs a 0x prefix.

Interview questions

How many bits is one hex digit?

Four. One hex digit covers values 0 to 15, so two digits describe one byte (0 to 255).

What does an 8-digit hex color mean in CSS?

The last two digits are alpha: #00000080 is black at about 50% opacity.

Analytics cookiesWe'd like to use analytics cookies to see which pages are useful. They're set only if you accept. Privacy Policy