Skip to content
Tutorials Center
My learning

Topics

Lesson 4 of 57 ยท Digital Foundations

BCD, Gray Code and ASCII

Learn why we use BCD, Excess-3, Gray code and ASCII or UTF-8, how each code works and where it is used, with live Python encoders and decoders.

Plain binary is only one way to turn information into bits. Engineers invent a code whenever a different pattern of bits has a practical advantage: easy display of decimal digits, safe readings from a rotating shaft, or a shared agreement on how letters are stored. Each code in this lesson exists to solve a specific problem, and knowing the problem makes the code easy to remember.

We will look at BCD and Excess-3 (decimal digits), Gray code (position sensors) and ASCII with UTF-8 (text), and write a small encoder or decoder for each in Python.

What is a code?

A code is an agreed mapping between things (digits, positions, characters) and bit patterns. The code in use must be known by both the sender and the receiver, because the same bits can mean different things: 0100 0001 is the number 65 in binary and the letter A in ASCII.

Four codes, four problems

BCD Show decimal digits exactly.
Excess-3 Make decimal complements easy.
Gray code Change one bit per step.
ASCII and UTF-8 Store letters and symbols.
1 / 2

BCD: Binary-Coded Decimal

Binary-Coded Decimal writes each decimal digit as its own 4-bit group (8-4-2-1 weights). The patterns 0000 to 1001 stand for the digits 0 to 9, and the six patterns 1010 to 1111 are unused (invalid in BCD).

The number 47 in BCD is 0100 0111 (4 and 7), while in plain binary it is 0010 1111. The BCD form is longer, since a byte can only hold 0 to 99 instead of 0 to 255, but it has one big advantage: converting to a display or a printed number needs no division. Each nibble maps directly to one digit, which is why calculators, digital clocks, meters and financial hardware use it. It also stores amounts like 0.10 exactly, with no binary rounding of decimal fractions.

The price shows up in arithmetic. Adding two BCD digits with a normal binary adder can give a result above 9, which is not a valid digit. The fix is decimal adjust: if a digit sum exceeds 9, or produces a carry, add 6 (0110) to skip over the six unused patterns.

Python BCD encode, decode and add

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Check the trace: 8 + 9 gives 17, which is above 9, so +6 is added and the digit becomes 7 with a carry. Then 3 + 4 + 1 = 8. The answer is 87, correct.

Excess-3

Excess-3 is BCD with 3 added to every digit: 0 is 0011, 1 is 0100, and 9 is 1100. It is not weighted, so it cannot be evaluated by adding place values, but it is self-complementing: flipping all four bits of a digit gives the 9's complement. For example 2 is 0101, flipped it is 1010 which is 7, and 2 + 7 = 9.

That made subtraction circuits for decimal machines simpler, and in addition the carry comes out correctly on its own (a digit sum above 9 produces a binary carry). You will rarely meet Excess-3 today, but it is a classic teaching example of a code designed for a purpose.

Python Excess-3 and its self-complementing property

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The assertion passes for every row, so the flipped Excess-3 code of each digit really is its 9's complement.

Gray code

Count in binary and look at the step from 7 to 8: 0111 becomes 1000, and all four bits change. In real hardware, bits never flip at exactly the same instant. A reader sampling in the middle of that step could see 1111, 0000 or any mixture, a reading that is wrong by a huge amount.

Gray code (reflected binary code) orders the patterns so that consecutive values differ in exactly one bit. A transition can then only ever be read as the old value or the new value, never as garbage. That is why Gray code is used in rotary and linear position encoders, in analog-to-digital converters and for passing counters between clock domains.

The conversion is a one-liner: gray = n ^ (n >> 1). To convert back, XOR together the shifted copies, or go bit by bit from the MSB, where each binary bit is the previous binary bit XOR the current Gray bit. The DSA lesson on Gray code and bit tricks covers the same formulas from the algorithm side.

Python Binary versus Gray code

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Look at the right-hand column: the Gray changes are always 1, even in the last row where the counter wraps from 15 back to 0. The binary column has steps with 4 bits changing (7 to 8 and 15 to 0). A reflected Gray code is also cyclic: the last pattern is one bit away from the first.

ASCII and Unicode

A computer stores text by giving every character a number, then storing that number in binary. ASCII (American Standard Code for Information Interchange) uses 7 bits, so 128 characters: the digits, the English letters in upper and lower case, punctuation, and 33 control codes such as newline.

A few anchors are enough to decode most of it:

Characters Decimal Hex
0 to 9 48 to 57 30 to 39
A to Z 65 to 90 41 to 5A
a to z 97 to 122 61 to 7A
space 32 20
newline 10 0A

The layout is smart. The code of a digit character is 0x30 plus the digit, so '7' is 0x37, and the low nibble is the digit itself, which is how a decoder turns a typed digit into BCD. An uppercase letter and its lowercase form differ by exactly one bit (value 32, bit 5), so toggling case in hardware is a single XOR or an AND gate.

ASCII cannot hold รฉ, ๆ—ฅ or an emoji. Unicode assigns a number (a code point) to every character in every language, and UTF-8 encodes those numbers as one to four bytes. The first 128 code points use one byte with the identical ASCII value, so every ASCII file is also valid UTF-8.

Python Text is just numbers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The plain letter A needs one byte, รฉ needs two, โ‚ฌ three and the emoji four. UTF-8 is therefore compact for English text yet able to store any script, which is why it is the dominant encoding of the web.

Code converters as circuits

Different parts of a system often use different codes: a counter produces binary, a display wants BCD, a sensor outputs Gray code. A code converter is a combinational circuit that translates one code into another. Designing one is a standard exercise in Boolean algebra and simplification, and it always follows the same recipe:

  1. Write the truth table: one row per valid input code, with the output code beside it.
  2. Mark the input combinations that can never occur as don't cares (see don't cares and hazards).
  3. Simplify each output bit with a Karnaugh map.
  4. Build the circuit from the resulting expressions, and verify it against the table.

BCD to Excess-3. The input is a BCD digit ABCD (0 to 9) and the output is WXYZ, the same digit plus 3. The six patterns 1010 to 1111 are not valid BCD, so they are don't cares for every output. Grouping the K-maps with those don't cares gives:

  • Z = D' (adding 3 always flips the least significant bit),
  • Y = CD + C'D' (an XNOR of C and D),
  • X = B'C + B'D + BC'D',
  • W = A + BC + BD.

Binary to Gray needs no K-map at all, because of the rule from the Gray code section: each Gray bit is the XOR of two neighboring binary bits, G3 = B3, G2 = B3 โŠ• B2, G1 = B2 โŠ• B1, G0 = B1 โŠ• B0. That is three XOR gates, all working in parallel. Gray to binary is the reverse, B3 = G3, B2 = B3 โŠ• G2, B1 = B2 โŠ• G1, B0 = B1 โŠ• G0, and here each gate needs the result of the previous one, so the three XOR gates form a chain and the delay grows with the number of bits.

Other common converters include BCD to binary (and back), Excess-3 to BCD, and BCD to seven-segment, a converter with four inputs and seven outputs, which you build step by step in the seven-segment project.

Python Two code converters, verified exhaustively

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The first table shows the circuit reproducing the Excess-3 code for all ten valid digits. What it outputs for the six invalid inputs (for example 1101 for 1010) is not meaningful, and that is fine: the don't cares let the simplification choose those outputs so that the equations became shorter. If the converter must also reject invalid codes, add an error output instead of using don't cares. The second table checks both Gray conversions on all sixteen values, and the last line states the cost difference: 3 XOR gates one level deep in one direction, 3 XOR gates three levels deep in the other.

Choosing a code

  • Need to show or compute in decimal digit by digit? BCD (or Excess-3 for its complement property).
  • Need safe readings while a value changes? Gray code.
  • Need to store letters? ASCII for English-only legacy data, UTF-8 for everything else.
  • Need compact arithmetic? Plain binary or two's complement.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the BCD representation of the decimal number 29?

    Each digit gets its own nibble: 2 is 0010 and 9 is 1001. The pattern 0001 1101 is plain binary for 29.
  2. 2. In BCD addition, a digit sum of 1100 (12) is corrected by adding which value?

    Six patterns (1010 to 1111) are unused in BCD, so adding 6 skips over them and produces a carry into the next digit.
  3. 3. Why is Gray code used in position encoders?

    With binary, several bits change at once and a reader can briefly see a very wrong value. With Gray code only one bit changes.
  4. 4. What is the Gray code of binary 0110 (6)?

    6 XOR (6 >> 1) = 0110 XOR 0011 = 0101.
  5. 5. How many bytes does UTF-8 use for the character A?

    Code points 0 to 127 are stored as a single byte equal to their ASCII value, so A is the single byte 0x41.

Summary

  • Code converters are designed from a truth table with don't cares: BCD to Excess-3 needs a few simplified gates, binary to Gray needs only XORs.
  • A code is an agreement between bit patterns and meanings; the same bits can mean different things in different codes.
  • BCD stores each decimal digit in 4 bits; adding digits needs a +6 correction when a sum exceeds 9.
  • Excess-3 adds 3 to each digit, which makes it self-complementing: flipping the bits gives the 9's complement.
  • Gray code changes exactly one bit between consecutive values (g = n ^ (n >> 1)), which avoids bad readings in position encoders.
  • ASCII maps 128 characters to 7-bit numbers; UTF-8 extends it to all of Unicode with one to four bytes per character.

Next: AND, OR and NOT Gates, where we start building logic itself.