Suppose you want to write hexadecimal data using only the digits 0 through 9. Obviously you could convert your number from base 16 to base 10. But suppose you want to do this in a way that is easy to carry out by hand.

You could store pairs of hex digits in triples of decimal digits. You could call this decimal-coded hex by analogy with binary-coded decimals from the early days of computers.

Let *n* = 16*x* + *y*, i.e. a number whose hex representation is *xy*. If either *x* or *y* is greater than 9, reduce it mod 10. Then tack on a third digit *z* to record which digits have been reduced: 0 for none, 1 for first, 2 for second, 3 for both.

Examples:

_{hex}→ 430

_{hex}→ 952

_{hex}→ 531

_{hex}→ 013

You could also put the extra digit *z* on the front. This would mean pairs of hexadecimal numbers map into the range 0–355 rather than be spread out more sparsely over 0–990.

Here’s Python code to make the encoding and decoding explicit.

def encode(n): assert(0 <= n < 256) a = n // 16 b = n % 16 c = 0 if a > 9: a %= 10 c += 1 if b > 9: b %= 10 c += 2 return 100*a + 10*b + c def decode(n): a = n // 100 b = (n // 10) % 10 c = n % 10 if c == 1: a += 10 if c == 2: b += 10 if c == 3: a += 10 b += 10 return a*16 + b