Spunk Autos

Websites and web tools

The Complete Hex Conversion Checklist

Hexadecimal, base 16, shows up in colour codes, file signatures, MAC addresses and debugging output. Converting it by hand is easy once you know the pattern, and a checklist stops the small errors that creep in. This page covers the method, worked examples and the mistakes to check for.

The basics

Hex uses sixteen digits: 0 to 9, then A to F for 10 to 15. Each hex digit is exactly four bits, so two hex digits make one byte, with values from 00 to FF, which is 0 to 255 in decimal.

Hex to decimal

Multiply the left digit by 16 and add the right digit. For larger numbers, each position to the left is worth 16 times more.

Decimal to hex

Divide by 16. The whole-number result is the left digit and the remainder is the right digit. For 200, 200 divided by 16 is 12 remainder 8, and 12 is C, so 200 is C8 in hex.

Colour code checklist

  1. Count the digits after the #. Three, four, six or eight are valid in CSS.
  2. Expand shorthand by doubling each digit: #ABC becomes #AABBCC, which is rgb(170, 187, 204).
  3. With eight digits, the last pair is alpha. 80 is 128, and 128 divided by 255 is about 0.502, so about 50 percent opacity.
  4. With four digits, the last digit is alpha in shorthand: #ABC8 becomes #AABBCC88.
  5. Remember that hex colour codes are case-insensitive: #1e90ff and #1E90FF are the same.
  6. Check that each pair converts to a value between 0 and 255.

Hex and binary

Because each hex digit is four bits, convert one digit at a time. A is 1010, F is 1111, so AF is 1010 1111. This is why hex is popular for showing bytes: it is compact and maps cleanly to bits.

Hex digits 8 to F
HexDecimalBinary
881000
991001
A101010
B111011
C121100
D131101
E141110
F151111

Notation in different places

  • CSS colours use a leading #.
  • C, JavaScript, Python and many other languages use a 0x prefix, such as 0xFF.
  • URLs use percent-encoding: %20 is the byte 0x20, a space.
  • MAC addresses separate bytes with colons or hyphens.
  • Some assembly and documentation styles use an h suffix, such as FFh.

Mistakes to check for

  • Confusing the letter O with zero or the letter I with one when reading codes aloud or from print.
  • Reading a multi-byte value in the wrong byte order; little-endian systems store the lowest byte first.
  • Treating a hex string as a decimal number in a spreadsheet, which drops leading zeros or converts to scientific notation.
  • Forgetting that alpha in CSS hex is at the end, while some other systems put it first.

For quick checks, programming languages convert in one line: in Python, int('1E', 16) gives 30 and hex(200) gives 0xc8.