Your country

Tools that support it use your country for local currency, number formats, units and paper size. Your choice is saved only in this browser.

Type a name or a two-letter code. Use the up and down arrow keys to move through the countries, Enter to choose one and Escape to close.

Computer Networks  Module 2 – Switching, performance and the physical layer

Signals, line coding and channel capacity

Hertz, baud and bit rate told apart, the Nyquist and Shannon limits worked in Python, and why links use NRZ, Manchester, 4B/5B, 64B/66B and PAM4.

  • Intermediate
  • 25 minutes
  • Examples run with Python 3.14.8 and Pyodide 314.0.7
  • By MySmartCoPilot
Free lesson, Pro answers: 25 minutes
Free: the whole lesson. With a pass: the model answers to its 2 interview questions.

What you will learn

  • Distinguish bandwidth in hertz, baud rate and bit rate
  • Apply the Nyquist and Shannon formulas to find maximum data rates
  • Convert signal-to-noise ratios between decibels and plain ratios
  • Explain NRZ, Manchester, 4B/5B, 64b/66b and PAM4 coding and why each exists

Before you start

A 3 kHz ideal low-pass channel with two real levels has a 6 kb/s Nyquist bound. Every link turns bits into something physical: a voltage on copper, a pulse of light in fibre, a radio wave. Three numbers describe that signal and are easy to confuse. Bandwidth in hertz is the range of frequencies the channel lets through. The symbol rate, in baud: Symbols transmitted per second; identical adjacent symbols need not create a signal transition., is how many signal elements (symbols) are sent each second. The bit rate is the symbol rate times the bits each symbol carries. Two limits bound the bit rate: Nyquist’s, for ideal zero-ISI real baseband signaling, gives twice the bandwidth as the symbol rate; Shannon’s, for a channel with noise, caps the bit rate itself at B log2(1 + S/N). How the bits become symbols is the job of the line code: A rule that represents data bits as signal levels or transitions on a physical link., and each code in use exists to fix a problem: keeping the receiver’s clock in step, leaving room for control signals, or squeezing more bits into each symbol.

A symbol’s alphabet connects baud to bit rate

The examples work through all three quantities with numbers you can run.

A symbol is one signal element: a voltage level held for a moment, one pulse, one point of a radio constellation. If a symbol can take M distinct values, it carries log2 M bits: 2 levels carry 1 bit, 4 levels 2 bits, and 256-QAM, a radio constellation of 256 points, 8 bits. The bit rate is therefore

bit rate=symbol rate×log2⁡M\text{bit rate} = \text{symbol rate} \times \log_2 M

The channel’s width in hertz limits the symbol rate, and the noise in it limits how many levels a receiver can tell apart. The diagram puts the pieces together.

The stated real-baseband model links bandwidth, symbol rate and bit rate; a Gaussian-noise capacity bound also constrains information.Ideal real basebandwidth B in hertzZero-ISI symbol rate:2B baud (Nyquist)Bit rate:symbol rate x log2 Mfor M levelsGaussian-noise bound:C = B log2(1 + S/N)S/N is a power ratiocapsx bits per symbolcan never exceed

From hertz to bits per second

Text description of the diagram

The diagram is a chain of four boxes from top to bottom.

  1. The channel width B, in hertz, for the stated ideal real-baseband model.
  2. An arrow labelled "caps" leads to the 2B-symbols-per-second zero-inter-symbol-interference signaling bound.
  3. An arrow labelled "x bits per symbol" leads to the bit rate, the symbol rate times log2 M for M signal levels.
  4. A dashed arrow labelled "can never exceed" leads to the capacity bound C = B log2(1 + S/N) for reliable information in the ideal Gaussian-noise model. S/N is a plain power ratio over the stated bandwidth; a practical code's achieved rate is a separate question.

At 1,000 symbols a second, four possible symbols carry two encoded bits each, giving 2,000 bit/s before further coding overhead. Changing between consecutive levels is not required: two identical symbols still occupy two symbol intervals. A measured transition count therefore cannot stand in for baud. The receiver has to identify both the symbol value and the boundary between adjacent symbols.

Checkpoint

Check: Symbols, transitions and encoded bits

  1. One question Two identical adjacent symbols occupy two symbol intervals without a level change. How many symbols were sent?

    Choose one answer.

    Show the answer: One question

    Answer: Two

    Baud counts symbol intervals per second, including adjacent identical values.

The Nyquist bound depends on a stated signaling model

For an ideal low-pass channel of bandwidth B and real symbols with zero inter-symbol interference, Nyquist signaling permits 2B symbols per second. This is the stated model, not a universal baud limit for every bandpass, multicarrier or deliberately interfering waveform. With M levels per symbol, the most a noiseless channel can carry is

CNyquist=2Blog2⁡MC_{\text{Nyquist}} = 2B \log_2 M

For a channel 3 kHz wide, about what an analogue telephone line passes, that is 6,000 bit/s with 2 levels and 24,000 bit/s with 16. On paper the rate grows without end as you add levels. In practice noise stops it: levels closer together than the noise can no longer be told apart.

For B = 3,000 Hz, 2B is 6,000 symbols a second; with 16 real levels, log₂16 = 4 bits per symbol and the bound is 24,000 bit/s. Follow those units in order, then compare two levels with sixteen:

Interactive · stage by stage Three kilohertz in the ideal real-baseband model Carry the units from channel bandwidth to symbols and then to encoded bits.
Three kilohertz in the ideal real-baseband model, step 4 of 4. Showing Bandwidth, Symbol rate, Two levels, Sixteen levels. In focus: Sixteen levels.BandwidthB = 3,000 HzSymbol rate2B = 6,000 baudTwo levels1 bit per symbolSixteen levels4 bits per symbol

The drawing shows the whole scene; its 4 steps are listed below.

Every step as text
  1. Bandwidth. The model is ideal real low-pass signaling with zero inter-symbol interference. Its bandwidth input is 3,000 Hz.
  2. Symbol rate. The Nyquist signaling bound gives 6,000 symbol intervals a second under these assumptions. This is not a transition count.
  3. Two levels. With M = 2, log₂M = 1, so the corresponding M-level bit-rate bound is 6,000 bit/s.
  4. Sixteen levels. With M = 16, log₂M = 4, so the corresponding bound is 24,000 bit/s. Noise and a practical code's performance need separate analysis.

This calculation assumes ideal pulse shaping and zero inter-symbol interference in the specified real low-pass model. It is not a promise that a chosen practical line code attains the bound, or a rule to apply unchanged to every bandpass or multicarrier signal.

Checkpoint

Check: The specified Nyquist signaling model

  1. One question Which context justifies applying the lesson's 2B real-symbol signaling bound?

    Choose one answer.

    Show the answer: One question

    Answer: Its ideal real low-pass, zero-inter-symbol-interference model

    State the bandwidth, signaling and interference assumptions before using the formula.

Shannon’s noisy-channel bound needs a power ratio

Shannon gave the limit for a channel with random (Gaussian) noise: no code, however clever, carries more than

C=Blog2⁡(1+SN)C = B \log_2\left(1 + \frac{S}{N}\right)

bits a second as the capacity bound for reliable communication with arbitrarily small error probability in the ideal band-limited additive white Gaussian noise model. Here signal-to-noise ratio: Signal power divided by noise power over the specified measurement bandwidth. is signal power divided by noise power over that bandwidth. Ratios are usually quoted in decibel: A logarithmic ratio unit; a power ratio has decibel value ten times its base-ten logarithm.: ITU-R V.574 defines the decibel value of a power ratio as 10 times its base-10 logarithm, so 10 dB is a ratio of 10, 20 dB of 100 and 30 dB of 1,000. Shannon’s formula needs the plain ratio, never the decibel number.

Nyquist, Shannon and decibels Python · capacity-study/capacity.py
# The specified bounds: ideal real low-pass, zero-ISI Nyquist signaling, and an ideal
# band-limited additive white Gaussian noise channel for Shannon. S/N is a power ratio.
from math import log2, log10, sqrt


def db_to_ratio(db):
    return 10 ** (db / 10)


def ratio_to_db(ratio):
    return 10 * log10(ratio)


for db in (0, 3, 10, 20, 30, 40):
    print(f"{db:2} dB = power ratio {db_to_ratio(db):>8,.1f}")

B = 3_000  # a channel 3 kHz wide, about what an analogue telephone line passes
print(f"Nyquist, B = {B:,} Hz:")
for levels in (2, 4, 16, 64):
    print(f"  {levels:2} levels: {2 * B * log2(levels):>7,.0f} bit/s")

snr = db_to_ratio(30)
print(f"Shannon at 30 dB: {B * log2(1 + snr):,.0f} bit/s")
# The two formulas meet where 2B log2(M) = B log2(1 + S/N), that is M = sqrt(1 + S/N).
print(f"where the two bounds meet at 30 dB: M about {sqrt(1 + snr):.1f}")
print(f"check: S/N of 1,001 is {ratio_to_db(1 + snr):.2f} dB")

Output

 0 dB = power ratio      1.0
 3 dB = power ratio      2.0
10 dB = power ratio     10.0
20 dB = power ratio    100.0
30 dB = power ratio  1,000.0
40 dB = power ratio 10,000.0
Nyquist, B = 3,000 Hz:
   2 levels:   6,000 bit/s
   4 levels:  12,000 bit/s
  16 levels:  24,000 bit/s
  64 levels:  36,000 bit/s
Shannon at 30 dB: 29,902 bit/s
where the two bounds meet at 30 dB: M about 31.6
check: S/N of 1,001 is 30.00 dB

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 capacity.py

Change B from 3,000 Hz to 4,000 Hz and compare the calculated bounds while keeping the level counts and SNR fixed.

Decibel Calculator (dB, dBm, dBV, dBu) Convert a signal-to-noise ratio between decibels and a plain ratio before you use it in Shannon's formula.

At 30 dB the stated 3 kHz Gaussian channel has a 29,902 bit/s capacity bound. The two formulas let you compare their bounds: setting 2B log2 M equal to B log2(1 + S/N) gives M = √(1 + S/N), about 31.6 here, so 32 levels make the Nyquist upper bound slightly exceed the Shannon bound in this comparison. Raising M further does not raise the smaller of these two bounds; achievable performance of a particular constellation and code is a separate question. Note that 3 dB is a factor of 2.0, a handy number for quick estimates: about 3 dB doubles or halves a power.

Step through the same 3 kHz, 30 dB case. The conversion gives 1,000; the formula uses 1 + 1,000, and only then takes a base-two logarithm:

Interactive · stage by stage Three kilohertz with a 30 decibel SNR Convert the power ratio before using the ideal Gaussian-channel capacity formula.
Three kilohertz with a 30 decibel SNR, step 4 of 4. Showing Power ratio, Formula argument, Bits per second, Wrong substitution. In focus: Wrong substitution.Power ratio10^(30 / 10) = 1,000Formula argument1 + S/N = 1,001Bits per second3,000 × log₂1,001Wrong substitution3,000 × log₂31

The drawing shows the whole scene; its 4 steps are listed below.

Every step as text
  1. Power ratio. Thirty dB refers to signal power divided by noise power over the stated bandwidth. Convert it to the plain ratio 1,000.
  2. Formula argument. The capacity formula uses 1 + the plain power ratio. It does not use 1 + the decibel value.
  3. Bits per second. The calculation gives about 29,902 bit/s under the ideal band-limited additive white Gaussian noise model.
  4. Wrong substitution. Putting 30 directly into the formula gives about 14,863 bit/s. That uses S/N = 30, which is a different channel from S/N = 1,000.

Its final 29,902 bit/s is a bound under the stated model. Substituting 30 directly gives about 14,863 bit/s and answers a different power-ratio problem.

Checkpoint

Check: Gaussian-channel capacity and power ratios

  1. One question What plain power ratio belongs in Shannon's formula when SNR is 30 dB?

    Type a number.

    Show the answer: One question

    Answer: 1000

    For powers, S/N = 10^(30/10) = 1,000.

Width scales the bound only when its SNR assumption holds

Shannon’s formula says capacity grows in proportion to bandwidth but only with the logarithm of the signal-to-noise ratio. The example works it out for the channel widths Wi-Fi uses, from 20 MHz to the 320 MHz channels that Wi-Fi 7 added in the 6 GHz band:

Shannon's limit for Wi-Fi channel widths Python · wifi-capacity-study/wifi_capacity.py
# Shannon's limit for the channel widths Wi-Fi uses, at three signal-to-noise ratios. One
# spatial stream; MIMO radios send several streams at once, each with its own limit.
from math import log2

WIDTHS_MHZ = (20, 40, 80, 160, 320)
SNRS_DB = (10, 20, 30)


def shannon_mbps(mhz, db):
    return mhz * 1e6 * log2(1 + 10 ** (db / 10)) / 1e6


print("width   " + "".join(f"{f'at {db} dB':>12}" for db in SNRS_DB))
for mhz in WIDTHS_MHZ:
    cells = "".join(f"{f'{shannon_mbps(mhz, db):,.0f} Mb/s':>12}" for db in SNRS_DB)
    print(f"{mhz:>3} MHz {cells}")

# Doubling the width doubles the limit; 10 dB more signal adds about 3.3 bits a second per hertz.
gain = log2(1 + 10 ** 3) - log2(1 + 10 ** 2)
print(f"20 dB -> 30 dB adds {gain:.2f} bit/s per hertz")

Output

width       at 10 dB    at 20 dB    at 30 dB
 20 MHz      69 Mb/s    133 Mb/s    199 Mb/s
 40 MHz     138 Mb/s    266 Mb/s    399 Mb/s
 80 MHz     277 Mb/s    533 Mb/s    797 Mb/s
160 MHz     554 Mb/s  1,065 Mb/s  1,595 Mb/s
320 MHz   1,107 Mb/s  2,131 Mb/s  3,190 Mb/s
20 dB -> 30 dB adds 3.31 bit/s per hertz

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 wifi_capacity.py

Holding S/N fixed, doubling the width doubles this bound, while going from 20 dB to 30 dB, ten times the signal power, adds only about 3.3 bit/s per hertz. That is why Wi-Fi 7 doubled its widest channel to 320 MHz, which the Wi-Fi Alliance credits with twice the throughput of Wi-Fi 6, and why denser constellations pay off only with a strong, clean signal: the Wi-Fi Alliance rates 4K-QAM, 12 bits a symbol, at 20 % more than the 10 bits of 1024-QAM. The table is for one stream; MIMO radios send several spatial streams at once, each with its own limit. Wide channels, dense constellations and several streams together are how IEEE 802.11be targets a maximum throughput of at least 30 Gbit/s.

The recorded table holds S/N constant while changing B. The scene follows its 30 dB column from 20 MHz through 40 MHz to 80 MHz: the rounded bounds are 199, 399 and 797 Mb/s. Each doubling is conditional on the same power ratio being retained.

Interactive · stage by stage The same power ratio across three channel widths Follow the recorded 30 dB column from 20 MHz to 40 MHz and 80 MHz; S/N stays 1,000.
The same power ratio across three channel widths, step 4 of 4. Showing 20 MHz, 40 MHz, 80 MHz, Check the comparison. In focus: Check the comparison.20 MHzabout 199 Mb/s40 MHzabout 399 Mb/s80 MHzabout 797 Mb/sCheck the comparisonstate B, S/N and streams

The drawing shows the whole scene; its 4 steps are listed below.

Every step as text
  1. 20 MHz. At 20 MHz and S/N = 1,000, the ideal single-stream Gaussian-channel bound is about 199 Mb/s. These are the table’s authored inputs.
  2. 40 MHz. At the same S/N, doubling B doubles the bound. Its rounded table value is 399 Mb/s.
  3. 80 MHz. Doubling B again with S/N still 1,000 gives the recorded 797 Mb/s rounded bound.
  4. Check the comparison. The proportional comparison holds the power ratio fixed. A measured channel needs its own SNR, stream and throughput evidence before these bounds can be applied.

An actual comparison needs the SNR of each channel being compared. Spatial streams and their SNRs also need their own model; neither a displayed PHY rate nor this single-stream bound proves speed-test throughput.

Checkpoint

Check: Bandwidth and noise assumptions

  1. One question Bandwidth doubles while the power ratio S/N stays fixed. What happens to the stated Gaussian-channel capacity bound?

    Choose one answer.

    Show the answer: One question

    Answer: It doubles

    With S/N fixed, the capacity bound is proportional to B, as the recorded width table shows.

Line-code transitions let a receiver recover timing

In these self-clocked serial-link examples, the receiver has no separate clock wire. It must recover the sender’s timing from the transitions in the signal itself, so a long stretch without a change leaves it guessing where one bit ends and the next begins. Three simple codes show the problem and the classic fix:

  • NRZ-L (non-return to zero, level): a 1 is high and a 0 is low for the whole bit. Simple and compact, but a run of identical bits is a flat line.
  • NRZI (non-return to zero, inverted): a 1 flips the level and a 0 keeps it. Runs of ones now have transitions; runs of zeros are still flat.
  • Manchester: every bit changes level in its middle. In the IEEE 802.3 convention, which 10 Mb/s Ethernet uses, a 1 goes from low to high and a 0 from high to low. The opposite convention also appears in some books and exam papers, so an answer should say which one it uses.

The protocol core below encodes the same byte, 01000001, as H and L levels. Each pair of letters occupies one bit interval. NRZI starts low and flips for a 1; Manchester uses the stated IEEE 802.3 convention:

One program · 14 languages Encode the same eight bits as H and L levels O(n) bit visits and emitted symbols for n bits

Python 3.14 · main.py

"""Encode the same byte with three explicitly stated level conventions."""


def encode(bits: str) -> tuple[str, str, str]:
    nrz, nrzi, manchester = [], [], []
    level = "L"
    for bit in bits:
        nrz.append("HH" if bit == "1" else "LL")
        if bit == "1":
            level = "H" if level == "L" else "L"
        nrzi.append(level * 2)
        manchester.append("LH" if bit == "1" else "HL")
    return "".join(nrz), "".join(nrzi), "".join(manchester)


bits = "01000001"
print(f"Bits: {bits}")
for name, wave in zip(("NRZ-L", "NRZI", "Manchester"), encode(bits)):
    print(f"{name}: {wave}")

Recorded with CPython 3.14.8 on macOS 26 arm64. It runs in your browser with Pyodide 314.0.7 (CPython 3.14.2). To run it yourself: python3 main.py

JavaScript Node 24 · main.mjs

const bits = "01000001";
const nrz = [],
  nrzi = [],
  manchester = [];
let level = "L";
for (const bit of bits) {
  nrz.push(bit === "1" ? "HH" : "LL");
  if (bit === "1") level = level === "L" ? "H" : "L";
  nrzi.push(level.repeat(2));
  manchester.push(bit === "1" ? "LH" : "HL");
}
console.log(`Bits: ${bits}`);
console.log(`NRZ-L: ${nrz.join("")}`);
console.log(`NRZI: ${nrzi.join("")}`);
console.log(`Manchester: ${manchester.join("")}`);

Recorded with Node.js 24.21.0 LTS (V8 13.6) on macOS 26 arm64. It runs in your browser with QuickJS (quickjs-emscripten 0.32.0). To run it yourself: node main.mjs

Java 25 LTS · Main.java

public class Main {
  public static void main(String[] args) {
    var bits = "01000001";
    var nrz = new StringBuilder();
    var nrzi = new StringBuilder();
    var manchester = new StringBuilder();
    char level = 'L';
    for (char bit : bits.toCharArray()) {
      nrz.append(bit == '1' ? "HH" : "LL");
      if (bit == '1') level = level == 'L' ? 'H' : 'L';
      nrzi.append(level).append(level);
      manchester.append(bit == '1' ? "LH" : "HL");
    }
    System.out.println("Bits: " + bits);
    System.out.println("NRZ-L: " + nrz);
    System.out.println("NRZI: " + nrzi);
    System.out.println("Manchester: " + manchester);
  }
}

Recorded with OpenJDK 25.0.4.1 LTS (Eclipse Temurin) on macOS 26 arm64. It runs in your browser with a TeaVM 0.16.0 build in QuickJS (quickjs-emscripten 0.32.0). To run it yourself: java Main.java

C++23 · main.cpp

#include <print>
#include <string>
#include <string_view>

int main() {
  const std::string_view bits = "01000001";
  std::string nrz, nrzi, manchester;
  char level = 'L';
  for (const char bit : bits) {
    nrz += bit == '1' ? "HH" : "LL";
    if (bit == '1')
      level = level == 'L' ? 'H' : 'L';
    nrzi.append(2, level);
    manchester += bit == '1' ? "LH" : "HL";
  }
  std::println("Bits: {}", bits);
  std::println("NRZ-L: {}", nrz);
  std::println("NRZI: {}", nrzi);
  std::println("Manchester: {}", manchester);
}

Recorded with Apple clang 21.0.0 (C++23) and GCC 16.2.0 on macOS 26 arm64. It runs in your browser with Clang in WebAssembly (YoWASP) 22.0.0-git20542-10. To run it yourself: clang++ -std=c++23 -O2 -Wall -Wextra -Werror -pedantic -fsanitize=address,undefined main.cpp -o main && ./main

C# 14 · .NET 10 · app.cs

using System.Text;

var bits = "01000001";
var nrz = new StringBuilder();
var nrzi = new StringBuilder();
var manchester = new StringBuilder();
var level = 'L';
foreach (var bit in bits)
{
    nrz.Append(bit == '1' ? "HH" : "LL");
    if (bit == '1') level = level == 'L' ? 'H' : 'L';
    nrzi.Append(level).Append(level);
    manchester.Append(bit == '1' ? "LH" : "HL");
}
Console.WriteLine($"Bits: {bits}");
Console.WriteLine($"NRZ-L: {nrz}");
Console.WriteLine($"NRZI: {nrzi}");
Console.WriteLine($"Manchester: {manchester}");

Recorded with C# 14 on .NET 10.0.12 (SDK 10.0.401) on macOS 26 arm64. It runs in your browser with the .NET runtime for WebAssembly 10.0.12. To run it yourself: dotnet run app.cs

C23 · main.c

#include <stdio.h>
#include <string.h>

int main(void) {
  const char bits[] = "01000001";
  char nrz[17] = {0}, nrzi[17] = {0}, manchester[17] = {0};
  char level = 'L';
  for (size_t pos = 0; pos < sizeof bits - 1; ++pos) {
    const char bit = bits[pos];
    memcpy(nrz + 2 * pos, bit == '1' ? "HH" : "LL", 2);
    if (bit == '1')
      level = level == 'L' ? 'H' : 'L';
    nrzi[2 * pos] = nrzi[2 * pos + 1] = level;
    memcpy(manchester + 2 * pos, bit == '1' ? "LH" : "HL", 2);
  }
  printf("Bits: %s\n", bits);
  printf("NRZ-L: %s\n", nrz);
  printf("NRZI: %s\n", nrzi);
  printf("Manchester: %s\n", manchester);
}

In C: The fixed buffers hold exactly two half-bit levels for each of the eight authored input bits, plus a terminator.

Recorded with Apple clang 21.0.0 (C23) and GCC 16.2.0 on macOS 26 arm64. It runs in your browser with Clang in WebAssembly (YoWASP) 22.0.0-git20542-10. To run it yourself: clang -std=c23 -O2 -Wall -Wextra -Werror -pedantic -fsanitize=address,undefined main.c -o main && ./main

PHP 8.5 · main.php

<?php

declare(strict_types=1);

$bits = '01000001';
$nrz = $nrzi = $manchester = '';
$level = 'L';
foreach (str_split($bits) as $bit) {
    $nrz .= $bit === '1' ? 'HH' : 'LL';
    if ($bit === '1') {
        $level = $level === 'L' ? 'H' : 'L';
    }
    $nrzi .= $level . $level;
    $manchester .= $bit === '1' ? 'LH' : 'HL';
}
echo "Bits: {$bits}\n";
echo "NRZ-L: {$nrz}\n";
echo "NRZI: {$nrzi}\n";
echo "Manchester: {$manchester}\n";

Recorded with PHP 8.5.11 (CLI) on macOS 26 arm64. It runs in your browser with php-wasm 0.2.0 (PHP 8.5.2). To run it yourself: php main.php

Rust 1.99 · main.rs

fn main() {
    let bits = "01000001";
    let mut nrz = String::new();
    let mut nrzi = String::new();
    let mut manchester = String::new();
    let mut level = 'L';
    for bit in bits.bytes() {
        nrz.push_str(if bit == b'1' { "HH" } else { "LL" });
        if bit == b'1' {
            level = if level == 'L' { 'H' } else { 'L' };
        }
        nrzi.push(level);
        nrzi.push(level);
        manchester.push_str(if bit == b'1' { "LH" } else { "HL" });
    }
    println!("Bits: {bits}");
    println!("NRZ-L: {nrz}");
    println!("NRZI: {nrzi}");
    println!("Manchester: {manchester}");
}

Recorded with rustc 1.99.0 (edition 2024) on macOS 26 arm64. It runs in your browser with a WebAssembly build on the WASI runner (browser_wasi_shim 0.4.2). To run it yourself: rustc --edition 2024 -O main.rs && ./main

TypeScript 6.0 · main.ts

const bits = "01000001";
const nrz: string[] = [],
  nrzi: string[] = [],
  manchester: string[] = [];
let level = "L";
for (const bit of bits) {
  nrz.push(bit === "1" ? "HH" : "LL");
  if (bit === "1") level = level === "L" ? "H" : "L";
  nrzi.push(level.repeat(2));
  manchester.push(bit === "1" ? "LH" : "HL");
}
console.log(`Bits: ${bits}`);
console.log(`NRZ-L: ${nrz.join("")}`);
console.log(`NRZI: ${nrzi.join("")}`);
console.log(`Manchester: ${manchester.join("")}`);

Recorded with TypeScript 6.0.3 (strict), run by Node.js 24.21.0 on macOS 26 arm64. It runs in your browser with QuickJS (quickjs-emscripten 0.32.0) after Sucrase 3.35.1. To run it yourself: npx -p typescript@6.0.3 tsc --noEmit --strict main.ts && node main.ts

Go 1.27 · main.go

package main

import (
	"fmt"
	"strings"
)

func main() {
	bits := "01000001"
	var nrz, nrzi, manchester strings.Builder
	level := byte('L')
	for _, bit := range bits {
		if bit == '1' {
			nrz.WriteString("HH")
			if level == 'L' {
				level = 'H'
			} else {
				level = 'L'
			}
			manchester.WriteString("LH")
		} else {
			nrz.WriteString("LL")
			manchester.WriteString("HL")
		}
		nrzi.WriteByte(level)
		nrzi.WriteByte(level)
	}
	fmt.Printf("Bits: %s\n", bits)
	fmt.Printf("NRZ-L: %s\n", nrz.String())
	fmt.Printf("NRZI: %s\n", nrzi.String())
	fmt.Printf("Manchester: %s\n", manchester.String())
}

Recorded with Go 1.27.1 on macOS 26 arm64. It runs in your browser with the Go compiler in WebAssembly 1.27.1. To run it yourself: go run main.go

Swift 6.4 · main.swift

let bits = "01000001"
var nrz: [String] = []
var nrzi: [String] = []
var manchester: [String] = []
var level = "L"
for bit in bits {
  nrz.append(bit == "1" ? "HH" : "LL")
  if bit == "1" { level = level == "L" ? "H" : "L" }
  nrzi.append(level + level)
  manchester.append(bit == "1" ? "LH" : "HL")
}
print("Bits: \(bits)")
print("NRZ-L: \(nrz.joined())")
print("NRZI: \(nrzi.joined())")
print("Manchester: \(manchester.joined())")

Recorded with Apple Swift 6.4 on macOS 26 arm64. It runs in your browser with a WebAssembly build on the WASI runner (browser_wasi_shim 0.4.2). To run it yourself: swiftc -O main.swift -o main && ./main

Ruby 4.0 · main.rb

# frozen_string_literal: true

bits = '01000001'
nrz = String.new
nrzi = String.new
manchester = String.new
level = 'L'
bits.each_char do |bit|
  nrz << (bit == '1' ? 'HH' : 'LL')
  level = level == 'L' ? 'H' : 'L' if bit == '1'
  nrzi << level << level
  manchester << (bit == '1' ? 'LH' : 'HL')
end
puts "Bits: #{bits}"
puts "NRZ-L: #{nrz}"
puts "NRZI: #{nrzi}"
puts "Manchester: #{manchester}"

Recorded with CRuby 4.0.7 on macOS 26 arm64. It runs in your browser with ruby.wasm 2.10.1 (Ruby 4.0.0). To run it yourself: ruby main.rb

Kotlin 2.4 · Main.kt

fun main() {
    val bits = "01000001"
    val nrz = StringBuilder()
    val nrzi = StringBuilder()
    val manchester = StringBuilder()
    var level = 'L'
    for (bit in bits) {
        nrz.append(if (bit == '1') "HH" else "LL")
        if (bit == '1') level = if (level == 'L') 'H' else 'L'
        nrzi.append(level).append(level)
        manchester.append(if (bit == '1') "LH" else "HL")
    }
    println("Bits: $bits")
    println("NRZ-L: $nrz")
    println("NRZI: $nrzi")
    println("Manchester: $manchester")
}

Recorded with Kotlin 2.4.20 on Java 25.0.4.1 on macOS 26 arm64. It runs in your browser with a WebAssembly build on the WASI runner (browser_wasi_shim 0.4.2). To run it yourself: kotlinc Main.kt -include-runtime -d main.jar && java -jar main.jar

Dart 3.13 · main.dart

void main() {
  const bits = '01000001';
  final nrz = StringBuffer();
  final nrzi = StringBuffer();
  final manchester = StringBuffer();
  var level = 'L';
  for (final bit in bits.split('')) {
    nrz.write(bit == '1' ? 'HH' : 'LL');
    if (bit == '1') level = level == 'L' ? 'H' : 'L';
    nrzi.write(level);
    nrzi.write(level);
    manchester.write(bit == '1' ? 'LH' : 'HL');
  }
  print('Bits: $bits');
  print('NRZ-L: $nrz');
  print('NRZI: $nrzi');
  print('Manchester: $manchester');
}

Recorded with Dart 3.13.5 on macOS 26 arm64. It runs in your browser with a WebAssembly build by dart2wasm 3.13.5. To run it yourself: dart run main.dart

What every language printed

Bits: 01000001
NRZ-L: LLHHLLLLLLLLLLHH
NRZI: LLHHHHHHHHHHHHLL
Manchester: HLLHHLHLHLHLHLLH

In an editable tab, change the authored eight-bit input to 00000000 and compare the three level strings. Keep eight input bits so the fixed C buffers still match this example.

Step through the first four bits and watch each code’s state. The NRZI level persists between bits; Manchester still has a middle transition for every zero.

Interactive · stage by stage The first four bits of 01000001 Compare NRZ-L, low-start NRZI that flips on 1, and IEEE-convention Manchester, two H/L half-bit levels per bit.
The first four bits of 01000001, step 4 of 4. Showing First bit: 0, Second bit: 1, Third bit: 0, Fourth bit: 0. In focus: Fourth bit: 0.First bit: 0LL / LL / HLSecond bit: 1HH / HH / LHThird bit: 0LL / HH / HLFourth bit: 0LL / HH / HL

The drawing shows the whole scene; its 4 steps are listed below.

Every step as text
  1. First bit: 0. NRZ-L holds low. NRZI starts low and keeps it for a zero. Manchester goes high to low in the middle of the bit.
  2. Second bit: 1. NRZ-L holds high; NRZI flips from low to high at the start. Manchester goes low to high in the middle.
  3. Third bit: 0. NRZ-L returns low. NRZI keeps the high state left by the preceding one. Manchester still has a middle transition.
  4. Fourth bit: 0. NRZI remains high for another zero, extending its flat interval. Manchester represents the zero with HL again, so timing transitions remain available.

The next measurement uses the same byte and two 64-bit runs. It prints the waveform and the longest flat interval; the high bar and underscore mean the same H and L levels as the program above:

NRZ-L, NRZI and Manchester for one byte Python · line-codes-study/line_codes.py
# Three ways to put bits on a wire, drawn as text: "‾" is a high level, "_" a low level,
# two characters per bit so that a change in the middle of a bit shows.

def nrz_l(bits):
    """1 is high, 0 is low, for the whole bit."""
    return "".join("‾‾" if b == "1" else "__" for b in bits)


def nrzi(bits, level="_"):
    """A 1 flips the level at the start of the bit; a 0 keeps it."""
    out = []
    for b in bits:
        if b == "1":
            level = "‾" if level == "_" else "_"
        out.append(level * 2)
    return "".join(out)


def manchester(bits):
    """IEEE 802.3: a 1 goes low to high in the middle of the bit, a 0 high to low."""
    return "".join("_‾" if b == "1" else "‾_" for b in bits)


def longest_flat(wave):
    """The longest stretch without a level change, in bit times."""
    longest = run = 1
    for a, b in zip(wave, wave[1:]):
        run = run + 1 if a == b else 1
        longest = max(longest, run)
    return longest / 2


letter = "A"
bits = format(ord(letter), "08b")
print(f"bits of {letter!r}:  " + " ".join(bits))
for name, code in (("NRZ-L", nrz_l), ("NRZI", nrzi), ("Manchester", manchester)):
    print(f"{name:11} {code(bits)}")

print("longest stretch without a change, in bit times:")
for label, stream in (("64 zeros", "0" * 64), ("64 ones", "1" * 64), (f"{letter!r}", bits)):
    flats = [longest_flat(code(stream)) for code in (nrz_l, nrzi, manchester)]
    print(f"  {label:9} NRZ-L {flats[0]:4g}   NRZI {flats[1]:4g}   Manchester {flats[2]:g}")

# Manchester needs two signal elements per bit, so 10 Mb/s Ethernet signals at 20 Mbaud.
print(f"10 Mb/s with Manchester: {10e6 * 2 / 1e6:g} million signal elements a second")

Output

bits of 'A':  0 1 0 0 0 0 0 1
NRZ-L       __‾‾__________‾‾
NRZI        __‾‾‾‾‾‾‾‾‾‾‾‾__
Manchester  ‾__‾‾_‾_‾_‾_‾__‾
longest stretch without a change, in bit times:
  64 zeros  NRZ-L   64   NRZI   64   Manchester 0.5
  64 ones   NRZ-L   64   NRZI    1   Manchester 0.5
  'A'       NRZ-L    5   NRZI    6   Manchester 1
10 Mb/s with Manchester: 20 million signal elements a second

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 line_codes.py

Number Base Converter See the bits of any byte in binary, as the example prints them for the letter A.

Manchester never goes more than one bit time without a change, but it pays for that with two signal elements per bit: 10 Mb/s Ethernet signals at 20 million elements a second. At higher speeds that doubling is too expensive, so faster links use block codes instead.

Key idea

A symbol interval and a signal transition are different things; a line code determines when transitions occur.

Checkpoint

Check: Clock recovery and line-code state

  1. One question The low-start NRZI encoder has just sent a 1 and now reads three zeros. Which level does it keep?

    Choose one answer.

    Show the answer: One question

    Answer: High for all three zeros

    The NRZI state persists across bits; a zero does not independently select a voltage.

Extra block bits have a cost measured against data bits

A block code maps every group of data bits to a slightly longer code group, chosen so that the stream always has enough transitions and some code groups are left over for control signals such as “start of frame” and “idle”.

  • 4B/5B turns 4 bits into 5. 100BASE-TX Ethernet sends its 4B/5B code groups at 125 million code bits a second for 100 Mb/s of data, scrambled, NRZI-encoded and carried as a three-level MLT-3 signal; Texas Instruments’ data sheet for its DP83848C transceiver lists the code groups and explains that the scrambler spreads the signal’s energy over a wide range of frequencies to keep radiated emissions down.
  • 8B/10B turns 8 bits into 10. The Linux kernel’s documentation describes 1000BASE-X as running at a fixed 1.25 Gbaud for 1 Gb/s of data.
  • 64B/66B adds a 2-bit header to every 64 bits, which also marks whether the block holds data or control. The kernel’s documentation gives 25GBASE-R, which uses the same coding as 10GBASE-R running 2.5 times as fast, a rate of 25.78125 Gbaud; 10GBASE-R itself runs at 10.3125 Gbaud.
4B/5B run lengths, overheads and PAM4 Python · block-codes-study/block_codes.py
# Measure data-to-code expansion; physical signaling after code bits is a separate stage.
from itertools import product
from math import log10

# The 16 data code groups of 4B/5B (100BASE-X): 4 data bits become 5 code bits.
FOUR_B_FIVE_B = ["11110", "01001", "10100", "10101", "01010", "01011", "01110", "01111",
                 "10010", "10011", "10110", "10111", "11010", "11011", "11100", "11101"]

# However two code groups follow each other, the longest run of zeros stays short. With NRZI
# (a 1 is a level change) that bounds the time without a transition.
longest = max(max(len(run) for run in (a + b).split("1")) for a, b in product(FOUR_B_FIVE_B, repeat=2))
print(f"4B/5B: longest run of zeros across any two data code groups: {longest} bits")
print(f"4B/5B: {32 - 16} of the 32 five-bit patterns are left for control codes and errors")


def si(value, unit):
    """100000000, 'b/s' -> '100 Mb/s'; 25781250000, 'baud' -> '25.78125 Gbaud'."""
    for factor, prefix in ((1e9, "G"), (1e6, "M")):
        if value >= factor:
            return f"{value / factor:.5f}".rstrip("0").rstrip(".") + f" {prefix}{unit}"
    return f"{value:g} {unit}"


for name, data, code, rate in (("4B/5B", 4, 5, 100e6), ("8B/10B", 8, 10, 1e9), ("64B/66B", 64, 66, 25e9)):
    overhead = (code - data) / data
    print(f"{name:7} overhead {overhead:7.3%}: {si(rate, 'b/s')} needs {si(rate * code / data, 'b/s')} of code bits")

# PAM4 sends 2 bits per symbol with four levels; NRZ sends 1 bit with two.
for name, bits in (("NRZ", 1), ("PAM4", 2)):
    per_symbol = f"{bits} bit{'s' if bits > 1 else ''} a symbol"
    print(f"{name:4} {2 ** bits} levels, {per_symbol}: 58 Gb/s needs {58 / bits:g} Gsym/s")
# On the same -1..+1 swing, PAM4's levels are 2/3 apart instead of 2: a third of the eye.
print(f"PAM4 eye height against NRZ: 1/3, a penalty of {20 * log10(3):.2f} dB")

Output

4B/5B: longest run of zeros across any two data code groups: 3 bits
4B/5B: 16 of the 32 five-bit patterns are left for control codes and errors
4B/5B   overhead 25.000%: 100 Mb/s needs 125 Mb/s of code bits
8B/10B  overhead 25.000%: 1 Gb/s needs 1.25 Gb/s of code bits
64B/66B overhead  3.125%: 25 Gb/s needs 25.78125 Gb/s of code bits
NRZ  2 levels, 1 bit a symbol: 58 Gb/s needs 58 Gsym/s
PAM4 4 levels, 2 bits a symbol: 58 Gb/s needs 29 Gsym/s
PAM4 eye height against NRZ: 1/3, a penalty of 9.54 dB

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 block_codes.py

On its own, before any scrambling, 4B/5B keeps the longest run of zeros across any two data code groups to 3 bits, and with NRZI each 1 is a transition, so the receiver sees a change at least every 4 bit times. Only 16 of the 32 five-bit patterns carry data; the rest supply the control codes and let the receiver spot invalid ones. The cost is 25 % more bits on the line, the same as 8B/10B, against 3.125 % for 64B/66B, which keeps its transitions by scrambling the data instead of mapping it through a table.

The overhead denominator is the original data. Follow 4 → 5 and 64 → 66 in the scene: their extra bits are 1/4 and 2/64 of the data, rather than 1/5 and 2/66 of the transmitted block. The physical signaling after those code bits is a separate layer of the calculation.

Interactive · stage by stage Count the extra bits against the original data Compare data-to-code expansion; the physical modulation that carries those code bits is a separate stage.
Count the extra bits against the original data, step 4 of 4. Showing 4B/5B, 8B/10B, 64B/66B, Use the right divisor. In focus: Use the right divisor.4B/5B1 extra / 4 data = 25%8B/10B2 extra / 8 data = 25%64B/66B2 extra / 64 = 3.125%Use the right divisordata bits, not code bits

The drawing shows the whole scene; its 4 steps are listed below.

Every step as text
  1. 4B/5B. Four data bits become five code bits. The line needs 125 million code bits a second for 100 million data bits a second; MLT-3 signaling follows further processing in 100BASE-TX.
  2. 8B/10B. Eight data bits become ten code bits. With binary signaling, 1 Gb/s of data therefore needs a 1.25 Gbaud coded line.
  3. 64B/66B. Sixty-four data bits gain a two-bit header. A 10 Gb/s binary-signaling line using this expansion runs at 10.3125 Gbaud.
  4. Use the right divisor. The fraction of transmitted bits used for overhead is a different quantity: 1/5, 2/10 or 2/66. It cannot replace the extra line-rate ratios above.

Checkpoint

Check: Block-code expansion

  1. One question A block expands 64 data bits to 66 code bits. How many percent extra line bits are added relative to data?

    Type a number.

    Show the answer: One question

    Answer: 3.125 %

    Two extra bits / 64 data bits × 100 = 3.125%.

Four amplitude levels trade symbol rate for smaller gaps

At tens of gigabits a second the channel’s loss grows quickly with frequency, so links send more bits per symbol instead of more symbols. PAM4: Four-level pulse amplitude modulation, carrying two encoded bits per symbol. (four-level pulse amplitude modulation) uses four signal levels, so each symbol carries 2 bits and the symbol rate halves. The Optical Internetworking Forum’s Common Electrical I/O agreement (CEI 4.0) defines 56 Gb/s-class electrical lanes both ways: NRZ lanes at up to 58 gigasymbols a second for very short reaches, and PAM4 lanes at up to 29, with the levels at +1, +1/3, −1/3 and −1. The price is in the gaps: on the same voltage swing PAM4’s levels are a third as far apart as NRZ’s two. With equal voltage-noise amplitude, that spacing comparison loses about 9.5 dB of margin; it does not set every implementation’s measured signal-to-noise requirement. The CEI agreement accepts that: its very-short-reach PAM4 lane needs a raw bit error ratio of only 10⁻⁶ and assumes forward error correction brings it to 10⁻¹⁵.

GATE CS

The cited GATE CS syllabus does not list the physical layer in its computer networks section, which starts at layering, switching and performance metrics. Treat this lesson as background for the questions it does list: bit rates and frame times in the data link layer, and the units behind every delay numerical.

Read the trade in this small table. The line-rate example is 58 Gb/s of encoded data, before any separate error-correction overhead; both alternatives use the same normalized −1 to +1 swing.

Quantity NRZ PAM4
Encoded bits per symbol 1 2
Symbol rate for 58 Gb/s 58 Gsym/s 29 Gsym/s
Adjacent level spacing on a two-unit swing 2 2/3

The spacing ratio is three, so the equal-voltage-noise eye-spacing comparison costs 20 log₁₀3 ≈ 9.54 dB. This is the stated comparison’s margin penalty, rather than a universal measured BER for every PAM4 device.

Follow the same encoded-rate and spacing comparisons one at a time in the scene:

Interactive · stage by stage Symbol rate and level spacing on the same swing Step through the same 58 Gb/s encoded-rate example, then compare adjacent voltage gaps.
Symbol rate and level spacing on the same swing, step 4 of 4. Showing NRZ, PAM4, Same two-unit swing, Eye-spacing comparison. In focus: Eye-spacing comparison.NRZ58 Gsym/sPAM429 Gsym/sSame two-unit swingspacing 2 versus 2/3Eye-spacing comparison20 log₁₀3 ≈ 9.54 dB

The drawing shows the whole scene; its 4 steps are listed below.

Every step as text
  1. NRZ. Two levels encode one bit per symbol. At 58 Gb/s of encoded data, binary signaling therefore needs 58 billion symbol intervals a second.
  2. PAM4. Four levels encode two bits per symbol. The same encoded bit rate therefore needs 29 billion symbol intervals a second, before separate error-correction overhead.
  3. Same two-unit swing. NRZ has one adjacent gap across the swing; PAM4 has three. The adjacent PAM4 spacing is one third of the NRZ spacing in this comparison.
  4. Eye-spacing comparison. The three-to-one spacing ratio gives the stated 9.54 dB comparison for equal voltage noise. An actual receiver and channel still determine its measured error rate.

Checkpoint

Check: Symbol rate and amplitude spacing

  1. One question Ignoring additional coding overhead, what symbol rate carries 58 Gb/s of encoded data with PAM4?

    Type a number.

    Show the answer: One question

    Answer: 29 Gsym/s

    Four levels carry log₂4 = 2 bits per symbol, so 58/2 = 29 Gsym/s.

Practise: Manchester code and Shannon’s limit

Exercise · Easy · Python

Manchester code and Shannon capacity

Write three functions, using the IEEE 802.3 convention for Manchester code (a 1 goes from low to high in the middle of its bit, a 0 from high to low). Signal levels are written as a string of "H" (high) and "L" (low), two letters per bit, one for each half of it.

  • manchester_encode(bits) takes a string of "0" and "1" and returns its levels: "10" becomes "LHHL".
  • manchester_decode(levels) turns levels back into bits. A string of odd length, or a bit whose two halves are the same ("HH" or "LL"), is not Manchester code: raise ValueError.
  • capacity(bandwidth_hz, snr_db) returns Shannon's limit in bits a second, with the signal-to-noise ratio given in decibels.

The encoder accepts binary strings only and the decoder accepts strings of valid H/L pairs only; otherwise raise ValueError. Empty strings round-trip to themselves. Bandwidth and SNR are integer or floating-point values, excluding booleans. Bandwidth is finite and nonnegative and the decibel SNR is finite; reject invalid values with ValueError. The numerical cases here stay within floating-point range. A negative decibel SNR is valid: it represents a plain power ratio below one.

Starter code · signals.py

import math


def manchester_encode(bits):
    """'10' -> 'LHHL' (IEEE 802.3: a 1 goes low to high, a 0 high to low, in the middle of the bit)."""
    # Replace this line with your code: it sends NRZ, one level per bit.
    return "".join("H" if b == "1" else "L" for b in bits)


def manchester_decode(levels):
    """'LHHL' -> '10'; raise ValueError when the levels are not Manchester code."""
    # Replace this line with your code.
    return ""


def capacity(bandwidth_hz, snr_db):
    """Shannon's limit in bits a second for a channel of bandwidth_hz with a signal-to-noise ratio of snr_db decibels."""
    # Replace this line with your code: it forgets to turn decibels into a ratio.
    return bandwidth_hz * math.log2(1 + snr_db)
The sample tests · test_signals.py
import math

from signals import capacity, manchester_decode, manchester_encode


def test_encode_one_and_zero():
    """a 1 is low then high, a 0 is high then low"""
    assert manchester_encode("1") == "LH"
    assert manchester_encode("0") == "HL"
    assert manchester_encode("10") == "LHHL"


def test_encode_a_byte():
    """the letter A, 01000001"""
    assert manchester_encode("01000001") == "HLLHHLHLHLHLHLLH"


def test_decode_round_trip():
    """decoding what was encoded gives the bits back"""
    for bits in ("", "0", "1", "1100101", "0" * 16):
        assert manchester_decode(manchester_encode(bits)) == bits


def test_decode_rejects_bad_levels():
    """a bit without its mid-bit transition, or half a bit, is not Manchester code"""
    for bad in ("HH", "LHLL", "LHH"):
        try:
            manchester_decode(bad)
        except ValueError:
            continue
        raise AssertionError(f"{bad!r} should raise ValueError")


def test_capacity_telephone_channel():
    """3 kHz at 30 dB: about 29.9 kb/s"""
    assert math.isclose(capacity(3_000, 30), 3_000 * math.log2(1_001), rel_tol=1e-9)


def test_capacity_scales_with_width():
    """doubling the bandwidth doubles the limit; 0 dB means S/N = 1, one bit a second per hertz"""
    assert math.isclose(capacity(40e6, 20), 2 * capacity(20e6, 20), rel_tol=1e-9)
    assert math.isclose(capacity(1e6, 0), 1e6, rel_tol=1e-9)

def test_nonbinary_input_is_rejected():
    for bits in ("02", "HL", "10x", 101):
        try:
            manchester_encode(bits)
        except ValueError:
            continue
        raise AssertionError(f"expected ValueError for {bits!r}")


def test_decoder_rejects_nonlevels():
    for levels in ("HX", "L0", "hl", 12):
        try:
            manchester_decode(levels)
        except ValueError:
            continue
        raise AssertionError(f"expected ValueError for {levels!r}")


def test_zero_width_and_negative_db():
    assert capacity(0, 30) == 0.0
    assert math.isclose(capacity(1_000, -10), 1_000 * math.log2(1.1), rel_tol=1e-9)


def test_invalid_capacity_parameters():
    for bandwidth, snr in [
        (-1, 30), (math.inf, 30), (1_000, math.nan),
        ("wide", 30), (None, 30), (True, 30),
        (1_000, "high"), (1_000, None), (1_000, False),
    ]:
        try:
            capacity(bandwidth, snr)
        except ValueError:
            continue
        raise AssertionError(f"expected ValueError for {(bandwidth, snr)}")
A hint

Map each bit to its pair of halves with a dictionary, {"1": "LH", "0": "HL"}, and decoding is the same dictionary the other way round, read two letters at a time. For the capacity, turn the decibels into a power ratio first: 10 ** (snr_db / 10), then use math.log2.

The sample tests run on this device, in your browser (Pyodide): nothing is sent to mysmartcopilot.com. The first run downloads Python (about 13.5 MB), which is kept for the next runs. A check in your browser is feedback for you, not proof that the code is right for every input.

Practice that adapts to you

Practise this lesson

15 questions about 7 ideas of this lesson. Each answer is explained at once, and what you get right is kept in this browser.

  1. Question 1 of 15 In the ideal real low-pass, zero-ISI model, B is 4 kHz and M is eight real levels. What is the 2B log₂M rate bound?

    Type a number.

    Show the answer: Question 1 of 15

    Answer: 24 kb/s

    2B = 8,000 symbols/s and log₂8 = 3 bits/symbol, so the bound is 24,000 bit/s under the stated model.

  2. Question 2 of 15 A signal-to-noise ratio is given as 20 dB. What is it as a plain power ratio?

    Type a number.

    Show the answer: Question 2 of 15

    Answer: 100

    For powers, dB = 10 log10(ratio), so the ratio is 10 to the power 20 / 10 = 100. Using 20 itself in Shannon's formula is the most common slip.

  3. Question 3 of 15 A channel is 1 MHz wide and its signal is 15 times as strong as its noise (a plain ratio, not decibels). What is its Shannon capacity, in Mb/s?

    Type a number.

    Show the answer: Question 3 of 15

    Answer: 4 Mb/s

    The ideal band-limited Gaussian-channel formula gives 1,000,000 × log₂16 = 4,000,000 bit/s. This is a reliable-information capacity bound under those assumptions, rather than a practical code's measured throughput.

  4. Question 4 of 15 Why can a receiver recover the clock from a Manchester-coded signal even during a long run of zeros?

    Choose one answer.

    Show the answer: Question 4 of 15

    Answer: Every bit has a middle transition under either convention

    A 0 goes high to low and a 1 low to high (IEEE 802.3), always in the middle of the bit, so the receiver sees a transition at least once per bit time. The price is two signal elements per bit: 20 Mbaud for 10 Mb/s.

  5. Question 5 of 15 Which statement compares the line codes correctly?

    Choose one answer.

    Show the answer: Question 5 of 15

    Answer: 64B/66B adds 3.125% relative to data, while 4B/5B and 8B/10B add 25%

    Overhead is the extra bits divided by the data bits: 1/4 for 4B/5B, 2/8 for 8B/10B and 2/64 for 64B/66B. PAM4 is not a block code at all: it carries 2 bits in every symbol, halving the symbol rate for the same bit rate.

  6. Question 6 of 15 What does baud count?

    Choose one answer.

    Show the answer: Question 6 of 15

    Answer: Symbols transmitted per second

    Symbol rate, transition count and application throughput are distinct.

  7. Question 7 of 15 A stream uses four symbols in its alphabet at 2,500 symbols/s. Before other overhead, what encoded bit rate follows?

    Type a number.

    Show the answer: Question 7 of 15

    Answer: 5000 bit/s

    log₂4 = 2 bits/symbol, so 2,500 × 2 = 5,000 bit/s.

  8. Question 8 of 15 In the specified Nyquist model, which factor converts symbol rate to the M-level bit-rate bound?

    Choose one answer.

    Show the answer: Question 8 of 15

    Answer: log₂M

    The unit conversion is symbols/s times encoded bits/symbol.

  9. Question 9 of 15 Which SNR form does B log₂(1 + S/N) require?

    Choose one answer.

    Show the answer: Question 9 of 15

    Answer: The plain signal-power/noise-power ratio over the stated bandwidth

    The noise power and bandwidth must accompany the signal-power ratio.

  10. Question 10 of 15 Which input is held fixed in the lesson's recorded Wi-Fi width table?

    Choose one answer.

    Show the answer: Question 10 of 15

    Answer: S/N at each listed decibel value

    A capacity comparison must identify what stays fixed as bandwidth moves.

  11. Question 11 of 15 An 80 MHz bound was calculated at S/N = 1,000. What evidence is needed before claiming the same scaling for a measured 160 MHz channel?

    Choose one answer.

    Show the answer: Question 11 of 15

    Answer: The SNR and other assumptions of the channel actually being compared

    The width table computes model bounds for fixed ratios. An actual comparison needs its own SNR and stream evidence, along with the constraints on measured throughput.

  12. Question 12 of 15 Manchester uses two signal elements per data bit. What element rate carries 10 Mb/s?

    Type a number.

    Show the answer: Question 12 of 15

    Answer: 20 million elements/s

    Two half-bit elements times ten million bits/s gives twenty million elements/s.

  13. Question 13 of 15 What does 4B/5B mean?

    Choose one answer.

    Show the answer: Question 13 of 15

    Answer: Four data bits become five code bits

    Code-bit expansion is distinct from the physical modulation carrying the coded stream.

  14. Question 14 of 15 What is the basic PAM4 trade on the same voltage swing?

    Choose one answer.

    Show the answer: Question 14 of 15

    Answer: Two encoded bits per symbol, with smaller adjacent level gaps

    The rate gain is conditional on distinguishing the closer levels reliably.

  15. Question 15 of 15 NRZ's adjacent spacing is 2 units while PAM4's is 2/3 on the same swing. What eye-spacing penalty does 20 log₁₀(spacing ratio) give?

    Type a number.

    Show the answer: Question 15 of 15

    Answer: 9.542425 dB (anything from 9.532425 to 9.552425 counts)

    The spacing ratio is 2 / (2/3) = 3, so 20 log₁₀3 is about 9.54 dB for this comparison.

Interview questions

What is the difference between baud rate and bit rate? (warm-up)

Baud rate is the number of symbols sent each second, not the number of transitions; bit rate is the number of bits sent each second. They are equal only when each symbol carries one bit. A symbol with M possible values carries log2 M bits, so the bit rate is the baud rate times log2 M: PAM4 at 29 gigasymbols a second carries 58 Gb/s, and 256-QAM carries 8 bits per symbol. Line codes can make the baud rate higher than the bit rate instead: Manchester sends two signal elements per bit, so 10 Mb/s Ethernet signals at 20 Mbaud. Bandwidth in hertz is a third quantity: in the ideal real-baseband, zero-ISI Nyquist model it bounds the baud rate at twice B, while noise limits reliably distinguishable information.

Model answers open with any pass: ₹79 for 1 week ($2.99), one payment that never renews.

  1. Fresher to mid

    A laptop shows an 80 MHz Wi-Fi channel at a 30 dB signal-to-noise ratio, yet a speed test reaches 400 Mb/s. Is that reasonable? Use Shannon's limit to explain the gap and say what would raise the rate.

    Model answer, Pro. Model answers open with any pass; prices are in the notice on this page. First step and follow-ups

  2. Mid to senior

    1000BASE-X uses 8B/10B coding, while 10GBASE-R uses 64B/66B. Why the change in these binary serial-line interfaces, and what does 64B/66B give up to get its lower overhead?

    Model answer, Pro. First step and follow-ups

Key takeaways

  • Bandwidth (Hz), symbol rate (baud) and bit rate (bit/s) are different quantities: bit rate = baud × log2 M.
  • Nyquist: the ideal real-baseband, zero-ISI model permits 2B symbols a second and bounds its M-level rate by 2B log2 M bit/s. Shannon’s ideal Gaussian-noise model bounds reliable information by B log2(1 + S/N) bit/s, with S/N as a plain power ratio (dB = 10 log10 of the power ratio).
  • Capacity grows in proportion to bandwidth but only logarithmically with signal-to-noise ratio, which is why radios widen their channels.
  • Line codes keep the receiver’s clock in step: Manchester has a transition in every bit (IEEE 802.3: 1 is low to high), at twice the symbol rate.
  • Block codes add transitions and control codes for less: 4B/5B and 8B/10B cost 25 %, 64B/66B 3.125 %.
  • PAM4 carries 2 bits per symbol and halves the symbol rate, at the cost of levels a third as far apart.

Terms in this lesson

baud
Symbols transmitted per second; identical adjacent symbols need not create a signal transition.
decibel
A logarithmic ratio unit; a power ratio has decibel value ten times its base-ten logarithm.
line code
A rule that represents data bits as signal levels or transitions on a physical link.
PAM4
Four-level pulse amplitude modulation, carrying two encoded bits per symbol.
signal-to-noise ratio
Signal power divided by noise power over the specified measurement bandwidth.

Corrections

  • Scoped self-clocking to the serial-link examples and the PAM4 penalty to an equal-swing, equal-voltage-noise spacing comparison.
  • Stated the Nyquist and Gaussian-channel assumptions, separated bounds from achievable code rates, and kept baud distinct from transition count.

References

Related tools

Report a problem with this lesson

Quick answers and tool search

Type to search tools or to get a quick answer, for example 18% of 2500. Use the up and down arrow keys to move through the results, Enter to choose, and Escape to close.