Most signed-encoding errors come from incorrect extension or silent mixing between std_logic_vector, signed and unsigned.
Gray code
Gray code changes one bit only between consecutive values. It is useful when a value is read during a mechanical or asynchronous transition.
Decimal
Binary
Gray
0
000
000
1
001
001
2
010
011
3
011
010
4
100
110
5
101
111
6
110
101
7
111
100
Common uses:
rotary encoder;
position measurement;
asynchronous FIFO pointers;
information crossing between two clock domains.
The goal is to reduce the risk of reading an incoherent intermediate value when several bits would otherwise change at the same time.
BCD
BCD (binary coded decimal) encodes each decimal digit on 4 bits.
12₁₀ = 0001 0010 in BCD12₁₀ = 0000 1100 in pure binary
BCD is less compact than pure binary, but it simplifies display-oriented interfaces: 7-segment displays, decimal input, watches and user-visible counters.
Codes 1010 to 1111 are not valid decimal digits in BCD.
8421 BCD is a weighted code: each position has a fixed weight.
Bit
Weight
b3
8
b2
4
b1
2
b0
1
For example, 0101 is 4 + 1 = 5.
Excess-3
Excess-3 is another 4-bit decimal encoding. Add 3 to the decimal digit, then encode the result as natural binary.
Digit
+3
Excess-3
0
3
0011
1
4
0100
5
8
1000
9
12
1100
It is not more compact than BCD, but it often appears in courses because it shows that a 4-bit word can follow a convention other than natural binary.
Parity
A parity bit adds a minimal amount of information to detect some transmission or storage errors.
With even parity, the total number of bits set to 1 must be even. In practice, the XOR of all protected bits and the parity bit must be 0.
Simple parity detects an error affecting an odd number of bits, but it does not tell which bit is wrong. It cannot correct the error by itself.
Hamming (7,4)
Hamming (7,4) protects 4 data bits with 3 parity bits. It produces a 7-bit word able to correct one single-bit error.
In the classic convention, power-of-two positions carry parity:
Position
1
2
3
4
5
6
7
Role
P1
P2
D1
P4
D2
D3
D4
During decoding, the parity equations are recomputed. The result is called the syndrome:
syndrome 0: no single-bit error detected;
non-zero syndrome: position of the likely faulty bit;
correction: flip the bit indicated by the syndrome.
Without an extra global parity bit, a classic Hamming (7,4) code does not correct two errors and does not always detect them cleanly. With global parity, it becomes a SECDED-style scheme: single-error correction, double-error detection.
Choosing the encoding
Need
Recommended encoding
Counter, address, size
unsigned
Arithmetic with positive and negative values
signed two's complement
Position read during a transition
Gray
Direct decimal display
BCD
Simple error detection
Parity
Single-bit error correction
Hamming
Masks, flags, frames
std_logic_vector
A good design states the encoding clearly in names, types and useful comments. This avoids implicit conversions and makes simulations easier to read.