Boolean Logic & Gates
Understanding AND, OR, NOT gates and how they combine into arithmetic logic units — the building blocks of every processor.
Read truth tables, derive XOR, build half and full adders, and simulate their sum and carry in Python. Optional notes cover physical signal hazards.
Introduction
Digital computers represent data as bits. AND, OR, and NOT gates combine to perform arithmetic, make decisions, and store values.
George Boole developed Boolean algebra in the 1840s. In 1937, Claude Shannon showed how to implement it with electrical circuits. Digital computers still rely on that connection.
Main Learning Path: Truth Table to Simulation
Work through these steps in order: read a truth table, derive a gate from its output column, use that gate to build adders, then check the result with a short simulation.
Truth Tables for Basic Gates
The inputs are bits, so each row lists one possible pair:
| A | B | NOT A | A AND B | A OR B | A XOR B |
|---|---|---|---|---|---|
| 0 | 0 | 1 | 0 | 0 | 0 |
| 0 | 1 | 1 | 0 | 1 | 1 |
| 1 | 0 | 0 | 0 | 1 | 1 |
| 1 | 1 | 0 | 1 | 1 | 0 |
NOT flips one input. AND is 1 only when both inputs are 1; OR is 1 when either input is 1. XOR is 1 when the inputs differ.
Derive XOR from Its Truth Table
Read the XOR column: its output is 1 for A=0, B=1 and for A=1, B=0. Those rows are covered by NOT A AND B and A AND NOT B, so:
A XOR B = (NOT A AND B) OR (A AND NOT B)
This derivation is the habit to practice: identify the rows where the output should be 1, then combine the input conditions for those rows.
Build a Half Adder and a Full Adder
A half adder adds two bits. Its sum is the XOR column; its carry is the AND column:
Sum = A XOR B
Carry = A AND B
A full adder also accepts an incoming carry bit Cin. Its sum is 1 when an odd number of its three inputs are 1. Its carry is 1 when at least two inputs are 1:
Sum = A XOR B XOR Cin
Carry = (A AND B) OR (Cin AND (A XOR B))
Chaining full adders makes a ripple-carry adder. The carry passes through each stage, so a wide adder may need more time to settle than a single-bit adder.
Short Python Simulation
The code uses integers 0 and 1, whose bitwise operators match these gates:
def half_adder(a, b):
return a ^ b, a & b
def full_adder(a, b, cin):
axb = a ^ b
return axb ^ cin, (a & b) | (cin & axb)
print("Half adder: A B | Sum Carry")
for a in (0, 1):
for b in (0, 1):
print(a, b, "|", *half_adder(a, b))
print("\nFull adder: A B Cin | Sum Carry")
for a in (0, 1):
for b in (0, 1):
for cin in (0, 1):
print(a, b, cin, "|", *full_adder(a, b, cin))
Check a few rows by hand against the truth table: 1 + 1 in a half adder produces sum 0 and carry 1; 1 + 1 + 1 in a full adder produces sum 1 and carry 1.
When This Knowledge Is Useful
Boolean logic is useful when reading bit masks and flags, debugging conditions that operate on bits, understanding instruction sets, or writing HDL for a circuit. For software-only work, the truth table and adder simulation are enough to start; physical timing and signal behavior are optional deeper topics.
Beyond the Core Path
Simplify Boolean Expressions
These laws help reduce a gate network while preserving its truth table:
A AND 1 = A;A OR 0 = AA AND NOT A = 0;A OR NOT A = 1- De Morgan:
NOT (A AND B) = NOT A OR NOT B - De Morgan:
NOT (A OR B) = NOT A AND NOT B
NAND, NOR, and Multiplexers
NAND and NOR are universal gates: either can express any Boolean function. For example, feeding the same signal into both NAND inputs makes a NOT gate; combining that with De Morgan’s laws gives AND and OR.
A 2-to-1 multiplexer chooses between inputs A and B using select bit S:
Output = (A AND NOT S) OR (B AND S)
From Gates to a CPU
An ALU combines arithmetic and logical circuits; registers store the values those circuits produce. The diagram shows where gates and adders fit into that larger system.
flowchart TB
subgraph "Transistor Level"
direction TB
A[Transistor] --> B[Inverter NOT]
A --> C[NAND Gate]
A --> D[NOR Gate]
end
subgraph "Basic Gates"
direction TB
C --> E[AND Gate]
D --> F[OR Gate]
B --> G[Buffer]
end
subgraph "Composite Gates"
direction TB
E --> H[XOR from AND/OR/NOT]
F --> H
B --> H
end
subgraph "ALU Components"
direction TB
H --> I[Adder Full Adder]
E --> J[AND Array]
F --> K[OR Array]
H --> L[ALU Control Unit]
end
subgraph "CPU"
direction TB
L --> M[Arithmetic Logic Unit]
M --> N[Register File]
M --> O[Data Bus Interface]
end
Optional Advanced: Hardware Hazards and Signal Integrity
These topics matter when building or debugging physical circuits. Complete the truth-table and adder simulation path first.
Floating CMOS Inputs
An unconnected input has no defined logic level and can pick up noise. A slowly changing or floating CMOS input can also remain near its switching threshold, where both transistors in an input stage may conduct and raise supply current. Texas Instruments explains the effect and design remedies in its application note, Implications of Slow or Floating CMOS Inputs.
Tie unused inputs to a documented high or low level. For microcontroller pins, configure the pin and its internal pull-up or pull-down as specified by the device documentation.
Mechanical Switch Bounce
A mechanical switch may make and break contact several times while moving between states. A digital circuit can read those transitions as multiple presses. Debounce the input in hardware, or sample it and accept a new state only after it remains stable for a chosen interval.
Static Hazards from Unequal Gate Delays
Boolean expressions describe settled outputs; real gates take time to change. For F = (NOT A AND B) OR (A AND C), set B = 1 and C = 1. The correct output stays 1 as A changes, but unequal path delays can briefly turn both product terms off and create a low glitch. Adding the redundant consensus term B AND C keeps the output high during that transition:
F = (NOT A AND B) OR (A AND C) OR (B AND C)
A zero-delay logic simulation will not show this timing hazard. Use timing-aware simulation or inspect the circuit with suitable measurement tools when the physical transition matters.
Implementation Snippets
Bitwise Operations in Bash
#!/bin/bash
# Bitwise operations demonstration
# Save as: bitwise_demo.sh
echo "=== Bitwise Operations ==="
# AND: Extract bits (masking)
value=0b11010110
mask=0b00001111
result=$((value & mask))
echo "$value & $mask = $result"
echo " (Extracts lower 4 bits: $(echo $result | awk '{printf "0b%08d\n", $1}'))"
# OR: Set bits
a=0b10100000
b=0b00001111
result=$((a | b))
echo "$a | $b = $result"
# XOR: Toggle bits
mask=0b00001111
toggled=$((value ^ mask))
echo "$value ^ $mask = $toggled"
# NOT: Invert all bits (using 8-bit representation)
result=$((~value & 0xFF)) # & 0xFF masks to 8 bits
echo "~$value = $result"
# Left/Right Shift
shift_left=$((value << 1))
shift_right=$((value >> 1))
echo "$value << 1 = $shift_left"
echo "$value >> 1 = $shift_right"
# Common uses
echo ""
echo "=== Common Use Cases ==="
# Check if bit 4 is set
if [ $((value & (1 << 4))) -ne 0 ]; then
echo "Bit 4 is SET in $value"
else
echo "Bit 4 is CLEAR in $value"
fi
# Set bit 2
new_val=$((value | (1 << 2)))
echo "Setting bit 2 in $value: $new_val"
# Clear bit 5
new_val=$((value & ~(1 << 5)))
echo "Clearing bit 5 in $value: $new_val"
# Toggle bit 0
new_val=$((value ^ 1))
echo "Toggling bit 0 in $value: $new_val"
Python Bit Manipulation Utilities
#!/usr/bin/env python3
"""
Bit manipulation utilities for embedded and systems programming
"""
from typing import Iterator
def bits(n: int, width: int = 0) -> Iterator[int]:
"""Yield each bit of n from LSB to MSB"""
while n:
yield n & 1
n >>= 1
def set_bit(value: int, bit: int) -> int:
"""Set bit to 1, return new value"""
return value | (1 << bit)
def clear_bit(value: int, bit: int) -> int:
"""Set bit to 0, return new value"""
return value & ~(1 << bit)
def toggle_bit(value: int, bit: int) -> int:
"""Toggle bit, return new value"""
return value ^ (1 << bit)
def get_bit(value: int, bit: int) -> int:
"""Get value of bit (0 or 1)"""
return (value >> bit) & 1
def extract_bits(value: int, start: int, width: int) -> int:
"""Extract a field of bits from a value
Args:
value: Source value
start: Bit position to start (0 = LSB)
width: Number of bits to extract
Returns:
Extracted value, right-aligned
"""
mask = (1 << width) - 1
return (value >> start) & mask
def create_field(value: int, start: int, width: int) -> int:
"""Create a field value positioned at start bits
Args:
value: Value to place in field
start: Bit position to start (0 = LSB)
width: Width of the field in bits
Returns:
Value with field inserted, suitable for ORing into target
"""
mask = ((1 << width) - 1) << start
return (value << start) & mask
def rotate_right(value: int, width: int, n: int) -> int:
"""Rotate bits right within specified width"""
n %= width
mask = (1 << width) - 1
value &= mask
return ((value >> n) | (value << (width - n))) & mask
def rotate_left(value: int, width: int, n: int) -> int:
"""Rotate bits left within specified width"""
n %= width
mask = (1 << width) - 1
value &= mask
return ((value << n) | (value >> (width - n))) & mask
# Example: Parsing ARM Cortex-M exception frame
def parse_arm_exception_frame(frame: int) -> dict:
"""Parse stacked registers from ARM exception
ARM exception frame layout on stack:
R0, R1, R2, R3, R12, LR, PC, XPSR
Each is 32 bits (4 bytes)
"""
return {
'xpsr': extract_bits(frame, 28, 4), # Actually only 2 bits matter for APSR
'pc': extract_bits(frame, 24, 8) << 2, # Stacked PC (thumb bit removed)
'lr': extract_bits(frame, 16, 8) << 2,
'r12': extract_bits(frame, 12, 4),
'r3': extract_bits(frame, 8, 4),
'r2': extract_bits(frame, 4, 4),
'r1': extract_bits(frame, 0, 4),
# R0 would be at frame - 4
}
if __name__ == "__main__":
# Demonstrate bit extraction
print("=== Bit Field Operations ===")
# Extract RGB components from 24-bit color: 0xRRGGBB
color = 0x4F2D9E # Some purple-ish color
r = extract_bits(color, 16, 8)
g = extract_bits(color, 8, 8)
b = extract_bits(color, 0, 8)
print(f"Color: 0x{color:06X}")
print(f" Red: 0x{r:02X} ({r})")
print(f" Green: 0x{g:02X} ({g})")
print(f" Blue: 0x{b:02X} ({b})")
# Modify a field in a register
# Example: Modify bits 8-11 in a 32-bit register
register = 0x12345678
print(f"\nOriginal register: 0x{register:08X}")
# Clear field and set new value
register = register & ~((0xF << 8)) # Clear bits 8-11
register = register | (0xA << 8) # Set to 0xA
print(f"After modifying bits 8-11 to 0xA: 0x{register:08X}")
Common Pitfalls / Anti-patterns
Pitfall: Misunderstanding operator precedence in C
In C, the bitwise operators have lower precedence than arithmetic and relational operators. a & 0xFF == 0 is parsed as a & (0xFF == 0), not (a & 0xFF) == 0. Always use parentheses.
Pitfall: Assuming two’s complement is universal While nearly universal now, systems could theoretically use other representations. For portable code, avoid assuming behavior on INT_MIN (which is -INT_MAX - 1 in two’s complement) or right-shifting signed integers (arithmetic vs logical shift is implementation-defined).
Pitfall: Ignoring fan-out limits Gates can only drive so many downstream inputs. Exceed the fan-out limit and signals degrade, causing intermittent failures. When designing, either use gates with higher drive strength or add buffer stages.
Pitfall: Using compound assignments incorrectly
a |= mask is not always equivalent to a = a | mask when a has side effects (like a[i++] |= mask where i changes behavior). Extract to separate statements.
Quick Recap Checklist
- Read gate outputs from the truth table for every input combination.
- Derive XOR as the OR of the two input rows where the output is 1.
- Half-adder sum/carry are XOR/AND; a full adder also takes an incoming carry.
- Use the Python simulation to check all half-adder and full-adder input rows.
- For physical circuits, account for propagation delay and floating inputs in the optional advanced section.
Interview Questions
A multiplexer (MUX) selects one of N inputs based on select lines. For a 2-to-1 MUX with select line S, input A, and input B:
Output = (A AND NOT S) OR (B AND S)
This can be visualized as:
- When
S = 0:Output = (A AND 1) OR (B AND 0) = A - When
S = 1:Output = (A AND 0) OR (B AND 1) = B
In C, this is equivalent to: output = (s ? b : a) or output = (a & ~s) | (b & s)
Larger MUXes (4-to-1, 8-to-1) are built by cascading smaller MUXes.
A latch is a level-sensitive storage element. A SR latch built from two NOR gates will continuously "reflect" its inputs when enabled. When the enable signal is high, the output changes immediately with input changes.
A flip-flop is edge-triggered — it only samples its inputs at the moment of a clock transition (rising or falling edge). This makes flip-flops easier to reason about in synchronous circuits because state changes only happen at known moments.
The most common flip-flop is the D flip-flop (D = Data), which stores the input value on each clock edge. The output only changes at that moment, making it suitable for building shift registers, counters, and state machines.
Key difference: Latches can cause timing issues and meta-stability problems more easily because they're transparent for longer. Most digital design uses flip-flops, not latches, for this reason.
Propagation delay is the time between an input change and the corresponding output change. Each gate has a characteristic delay (typically 1-10 nanoseconds for CMOS). In a chain of gates, delays accumulate.
Consider a ripple-carry adder: the carry must propagate through every full adder stage. If each stage has 2ns delay, a 32-bit adder needs 64ns just for carry propagation — making it slow.
Critical path analysis identifies the longest delay path in a circuit, determining the maximum clock frequency. Shorter paths can be intentionally slowed with delay elements to match timing.
Hazards occur when different paths have different delays. If input changes and one path is faster than another, the output may brieflyglitch to an incorrect value before settling. This is why asynchronous (unclocked) combinational logic is problematic.
Meta-stability occurs when a flip-flop's input is changing near the clock edge, violating the setup or hold time. The flip-flop cannot resolve to a stable 0 or 1 in the required time.
The output may oscillate or settle to an intermediate voltage that's neither a valid high nor low. This metastable state eventually resolves (randomly to 0 or 1), but the resolution time can exceed the clock period.
In practice, meta-stability is solved by adding a synchronizer — typically two flip-flops in series. The first may go meta-stable, but the second almost always sees a stable value. The Mean Time Between Failures (MTBF) depends on the clock frequency and the flip-flop's meta-stable recovery time.
This matters when crossing clock domains — an asynchronous signal (like a button press) being sampled by a synchronous system. Without synchronization, meta-stability can cause intermittent, hard-to-reproduce bugs.
A half adder adds two single bits and produces a sum and a carry output. It cannot handle an incoming carry from a previous stage.
Sum = A XOR BCarry = A AND B
A full adder adds three bits: the two operands plus an incoming carry from a previous stage. This enables chaining multiple full adders to create N-bit adders.
Sum = A XOR B XOR CinCarry = (A AND B) OR (Cin AND (A XOR B))
The carry chain is what makes ripple-carry adders slow—each stage must wait for the previous carry to settle. More advanced designs (carry-lookahead, carry-skip) reduce this delay at the cost of more hardware.
A decoder converts a binary-encoded value into a one-hot representation. For an N-to-2^N decoder, there are N inputs and 2^N outputs, where exactly one output is high corresponding to the input value.
For a 2-to-4 decoder:
- Enable must be active for any output to be high
- When Enable=1: Y0=NOT A AND NOT B, Y1=NOT A AND B, Y2=A AND NOT B, Y3=A AND B
Each output is an AND of Enable with the appropriate combination of input polarities. Decoders are fundamental building blocks for:
- Memory address decoding
- Control signal selection
- Demultiplexing data streams
Combinational logic output depends only on current inputs. Given the same inputs, the output is always the same regardless of previous history. Examples: adders, multipliers, MUX, decoder.
Sequential logic output depends on both current inputs and previous state (memory). These circuits use feedback loops and storage elements (flip-flops, latches). Examples: counters, shift registers, state machines.
The key distinction is time: combinational logic is instantaneous (modulo propagation delay), while sequential logic has memory and evolves based on clock transitions or events.
Fan-out is the number of gate inputs that a single output can drive without degrading signal quality. Each input adds load (capacitance) to the driving output.
If you exceed fan-out limits:
- Signal rise/fall times increase (slower transitions)
- Voltage levels degrade (logic low might not be low enough)
- Noise margin decreases, making circuit susceptible to interference
- Eventually, logic gates may not recognize the signal as valid
Solutions include using buffers (which have higher drive strength) or splitting the signal through multiple drivers. When designing, check datasheet fan-out specifications and account for loading from wire capacitance too.
A Karnaugh map (K-map) is a visual method for simplifying Boolean expressions using a grid layout where each cell represents a minterm. Cells are arranged so adjacent cells differ by only one variable, making it easy to identify groups of 1s that can be simplified.
Groups must be powers of 2 (1, 2, 4, 8) and can wrap around edges. The larger the group, the simpler the resulting product term — a group of 4 eliminates 2 variables.
Example: For F = Σ(0, 2, 5, 7) with don't cares at m1 and m6, draw a 4×4 K-map and group the 1s. The grouping reveals that F = B' + D (simpler than the sum-of-products form).
K-maps work up to 4 variables directly; beyond that, Quine-McCluskey or algorithmic methods are used. The goal is minimizing the number of terms and literals to reduce gate count in hardware implementation.
Static logic maintains its output state continuously through some direct connection to power rails. The output is always either pulled high or pulled low by some network of transistors. CMOS is the dominant static logic family: at any moment, the output is driven by either the pull-up network (PMOS) or pull-down network (NMOS), never floating.
Dynamic logic stores values temporarily on capacitance (node capacitance) and relies on clocked precharging and evaluation. The output is not continuously maintained—it's evaluated during a clock phase. Domino logic, domino CMOS, are examples.
Dynamic logic advantages:
- Faster (fewer transistors in evaluation path)
- Lower power (only one network evaluates at a time)
- Smaller area (can share precharge transistors)
Dynamic logic disadvantages:
- Charge leakage (stored charge degrades over time)
- More sensitive to noise (lower noise margin)
- More complex design and testing
- Clock skew problems
Modern processors mostly use static CMOS for reliability, but some high-performance sections use dynamic logic where speed is critical.
A state machine (finite state machine, FSM) is a computational model that transitions between a finite number of states based on inputs and current state. State machines control digital logic, embedded systems, and protocol implementations.
Implementation using flip-flops:
State encoding: Assign each state a binary value. With N flip-flops, you can represent 2^N states.
# Example: 2-bit state encoding for traffic light
# States: 00=Red, 01=Yellow, 10=Green
STATE_BITS = 2
state = 0b00 # Start at Red
State transition logic (combinational)
next_state = (
(state == 0b00) & INPUT & 0b01) | # Red -> Yellow on timer
(state == 0b01) & INPUT & 0b10) | # Yellow -> Green
(state == 0b10) & INPUT & 0b00) # Green -> Red
State register: Flip-flops store the current state. On each clock edge, the next state becomes the current state.
Output logic: Combinational logic maps current state (and optionally inputs) to outputs. Two types:
- Moore machine: Outputs depend only on current state
- Mealy machine: Outputs depend on current state and inputs
State machines are fundamental: protocol implementations (TCP state machine), digital controllers (vending machine), and sequencers (instruction decode pipeline).
Synchronous reset: The reset signal is sampled on the clock edge. The flip-flop only resets when both the clock edge occurs AND the reset signal is active. The reset propagates through the pipeline with the clock.
always @(posedge clk) begin
if (reset) // Synchronous reset - evaluated at clock edge
q <= 0;
else
q <= d;
end
Asynchronous reset: The reset takes effect immediately, not waiting for the clock edge. The flip-flop has a dedicated reset pin that overrides normal operation.
always @(posedge clk or posedge async_reset) begin
if (async_reset)
q <= 0;
else
q <= d;
end
Synchronous reset advantages:
- Cleaner timing analysis (reset is just another signal)
- No timing violations on reset (happens at known time)
- Works correctly with clock enable
Asynchronous reset advantages:
- Works immediately (doesn't need clock to reset)
- Simpler to implement (reset is immediate)
- Guaranteed reset even if clock is missing
Many designs use both: asynchronous reset for fast reset capability, with synchronization logic to ensure proper reset release timing.
A clock tree is a distributed network of buffers that delivers the clock signal to all sequential elements (flip-flops, latches) in a synchronous circuit. The goal is to ensure the clock arrives at all elements at approximately the same time.
Clock skew is the difference in arrival times of the clock at different elements. It occurs because different paths have different lengths and propagation delays.
Effects of clock skew:
- Setup time violations: If clock to register B arrives later than expected, data from register A may not be stable when B samples
- Hold time violations: If clock to register B arrives earlier, it might sample before register A's data is ready
- Reduced timing margin: Skew eats into the available time for computation
Clock skew is managed through:
- Clock tree synthesis: Balanced tree structure with equal path lengths
- Clock gating: Disabling clock to unused areas (also saves power)
- PLL/DCM: Clock conditioning modules that deskew and multiply/divide clocks
In FPGAs, dedicated clock routing resources (global buffers, regional clocks) minimize skew. In ASICs, custom clock tree design is critical for timing closure.
A decoder converts a binary input (N inputs) into a one-hot output (2^N outputs). One output is active for each input combination. For example, a 3-to-8 decoder has 3 inputs and 8 outputs; input 101 selects output 5.
A demultiplexer (DEMUX) takes a single data input and routes it to one of several outputs based on select lines. It's essentially a decoder with an added data input—the decoder's enable line becomes the data input.
Relationship:
- A 1-to-2^n DEMUX can be implemented using an n-to-2^n decoder
- The decoder's outputs become the DEMUX outputs
- The select lines are the decoder's inputs
Uses:
- Decoder: Memory address decoding, selecting one of many memory chips
- Demultiplexer: Routing serial data streams, distributing clock signals
Combined, decoder/demux are fundamental building blocks for memory systems and digital displays.
A shift register is a cascade of flip-flops where the output of one becomes the input of the next. Each clock pulse shifts the data one position left or right.
Common types:
- SISO (Serial In, Serial Out): Data shifts in one end, out the other. Used for time delay.
- SIPO (Serial In, Parallel Out): Data shifts in serially, all bits available in parallel. Used for serial-to-parallel conversion (e.g., reading ADC data).
- PISO (Parallel In, Serial Out): Parallel load, then shift out serially. Used for serial transmission of parallel data.
- PIPO (Parallel In, Parallel Out): Parallel load, parallel output. Essentially a register.
Applications:
- Data delay: SISO creates a time delay equal to (number of stages) × clock period
- Serial communication: PISO for transmitter, SIPO for receiver
- Multiplication/division: Shift left multiplies by 2, shift right divides by 2
- Ring counters: Feedback from output to input creates a rotating pattern
A multiplexer (MUX) selects one of N inputs and forwards it to a single output. The select lines determine which input is connected to the output.
A demultiplexer (DEMUX) takes a single input and routes it to one of N outputs. The select lines determine which output receives the input.
Key difference:
- MUX: N inputs → 1 output (selector)
- DEMUX: 1 input → N outputs (router)
They are inverses of each other. A MUX followed by a DEMUX with the same select lines creates a path from one source to one destination (like a crossbar switch).
Note: A 2-to-1 MUX and a 1-to-2 DEMUX are actually the same circuit with different usage—the select line controls whether input A or B connects to output (MUX) or whether input connects to output A or B (DEMUX).
A parity bit is a single bit added to a data word to enable detection of single-bit errors. It makes the total number of 1s either even (even parity) or odd (odd parity).
Even parity: If data has odd number of 1s, parity bit = 1 (making total even). If data has even number of 1s, parity bit = 0.
Odd parity: Opposite—if data has odd number of 1s, parity bit = 0.
Error detection:
- Sender computes parity bit and appends to data
- Receiver counts 1s in received word including parity bit
- If parity doesn't match expectation, an error occurred
Limitations:
- Detects only odd number of bit errors (1, 3, 5...)
- Does not detect 2-bit errors (even parity would be correct)
- Cannot correct errors (only detects)
Parity is used in: UART transmission (7 data + 1 parity), RAM error detection (simple ECC), and as building blocks for more complex error correction codes.
A Gray code counter advances through Gray code sequence, where only one bit changes between successive values. Unlike binary counting where multiple bits can change (e.g., 011 to 100), Gray code has exactly one bit transition.
Binary Gray
000 000
001 001
010 011
011 010
100 110
101 111
110 101
111 100
Uses:
- Rotary encoders: Position sensors where a single track changes at a time—if the sensor samples mid-transition, only one bit is uncertain
- Asynchronous sampling: When sampling signals that may change at any time, Gray code prevents invalid intermediate states
- State machine encoding: When transitioning between states, only one bit changes—simplifies timing analysis
In binary, a change from 011 to 100 (all 3 bits flip) can cause glitches if different paths have different delays. In Gray code, only one bit flips, so there's no ambiguity.
An encoder converts a one-hot input (one input line is high, others low) into a binary output representing the index of the active input. 4-to-2 encoder: if input 3 is high, output is 11 (binary for 3).
A priority encoder handles multiple active inputs by prioritizing and outputting the highest-priority active input. If inputs 2 and 5 are both high, it outputs 5 (if 5 has higher priority).
Priority encoder behavior:
Input: 10010 (inputs 1 and 4 active)
Output: 4 (the highest index active)
Common use cases:
- Interrupt controllers: Multiple devices can request interrupts; priority encoder selects highest priority
- Memory arbitration: Multiple masters request bus access; highest priority wins
- Rotary switches: Convert multiposition switch position to binary
The priority encoder often has a valid output bit (V) indicating if any input is active. This distinguishes "no active input" from "input 0 active."
An equality detector (also called XNOR gate array) checks if two N-bit values are exactly equal. Each bit pair is compared; if all pairs match, the output is 1. Simple: just XNOR each bit, then AND all results.
equal = (a[0] XNOR b[0]) & (a[1] XNOR b[1]) & ...
A magnitude comparator determines the relationship between two N-bit values: A > B, A < B, or A = B. This is more complex than equality—it must examine the most significant bits where the values differ.
A > B: MSB difference where A=1, B=0, or all higher bits equal
A < B: MSB difference where A=0, B=1, or all higher bits equal
A = B: All bit pairs equal
Implementation uses a chain of 1-bit comparators that propagate the result from MSB to LSB:
- Compare most significant bits
- If they differ, that's the result
- If they're equal, continue to next bit
Equality detector: Used in cache tag comparison, branch condition checking. Magnitude comparator: Used in control flow (branch on less than), sorting networks, address decoding.
Further Reading
- Digital Logic Circuits — All About Circuits digital textbook
- nandgame.com — Build a CPU from NAND gates in your browser
- HDLBits — Verilog practice problems for digital design
- Introduction to Digital Logic with Laboratory Exercises — Free textbook on digital logic design
- Complementary MOS (CMOS) fundamentals — University course notes on CMOS operation
- How Computers Work — From gates to complete computer systems
- Instruction Set Architecture — The interface these hardware units expose to software
Conclusion
Boolean logic supplies the basic operations used by digital circuits. AND, OR, and NOT gates combine into adders, control logic, storage circuits, and ALUs.
Truth-table reasoning helps check gate behavior and bit-level code. The optional hardware section adds timing effects that truth tables do not show.
Next, build a simple CPU simulator to see how these gates fit into a processor, or read about instruction set architecture to learn how software uses processor instructions.
Category
Related Posts
ASLR & Stack Protection
Explore ASLR, PIE, stack canaries, and NX on Linux with GCC, then inspect a harmless C program to see what each mitigation does and where it falls short.
Assembly Language Basics: Writing Code the CPU Understands
Learn x86-64 Linux assembly with the System V ABI: track registers, assemble and run a small program, debug it in GDB, then compare AArch64.
Boot Process
How firmware, bootloaders, kernels, and user space start an operating system, with Linux/x86 BIOS/MBR and UEFI paths plus practical troubleshooting.