Huffman & Shannon-Fano Tree
Compare optimal prefix codes, entropy, and compression entirely in your browser.
Examples
Uniform four-symbol input
abcdcodes: a=00 b=01 c=10 d=11, entropy 2.0, encodedBits 8, originalBits 32, average length 2Equal frequencies produce fixed-length 2-bit codes; entropy equals the achieved rate, so no further prefix-code gain is possible.
Single repeated symbol
aaaentries: [{ char: "a", frequency: 3, probability: 1, huffmanCode: "0", shannonFanoCode: "0" }], encodedBits 3, entropy 0One distinct symbol needs no branching, so both builders assign the single-bit code 0 and entropy collapses to zero.
About this tool
Huffman Shannon Tree runs analyzeText over the input, splitting it into Unicode code points with [...text] so emoji count as single symbols, then counting frequencies per symbol. It builds both a Huffman tree (repeatedly merging the two lowest-frequency nodes from a queue ordered by frequency then minChar) and a Shannon-Fano tree (sorting symbols by descending frequency then character, then recursively splitting at the point minimizing |total - 2 * leftTotal|). Both trees are walked to prefix-free binary codes, and entries are returned sorted by character with frequency, probability, huffmanCode, and shannonFanoCode per symbol.
Aggregates are derived from the Huffman codes: encodedBits is the frequency-weighted Huffman length, averageCodeLength is encodedBits divided by symbol count, entropy is the Shannon -sum(p * log2(p)) bound in bits per symbol, originalBits assumes 8 bits per symbol, and compressionRatio and savingsPercent compare encodedBits against that 8-bit baseline. A single repeated symbol receives code 0, so aaa encodes in 3 bits with zero entropy; uniform inputs such as abcd receive equal-length codes (2 bits each, entropy exactly 2). Empty input yields zeroed aggregates, an empty entry list, and undefined trees.
Tie-breaking is fully deterministic: Huffman orders nodes by frequency then lexicographic minChar, and Shannon-Fano orders by descending frequency then character, so anagrams like abcd and dcba produce identical codes. Non-printing symbols render with formatSymbol (space as ␠, newline as ↵, tab as ⇥). Every emitted code is a non-empty binary string, and both code sets are prefix-free, matching the prefix property DEFLATE-style Huffman coding relies on.
How to use this tool
Enter text to analyze
Paste or type any string. Frequencies are counted per code point, so multi-byte emoji are single symbols, and the entry table plus both code sets update from the counts.
Compare the two code tables
Read huffmanCode and shannonFanoCode side by side per symbol. Huffman minimizes the weighted length; on skewed inputs such as AAAAAAABBBCCDE the Shannon-Fano total meets or exceeds it.
Read entropy versus average length
Use entropy as the theoretical floor and averageCodeLength as the achieved Huffman rate. The gap between them is the redundancy left in the code.
Check the size win
Compare encodedBits against originalBits (length × 8) via compressionRatio and savingsPercent to see the headline saving under the tool's fixed 8-bit baseline.
Use cases
Teaching entropy coding
Contrast Huffman optimality against Shannon-Fano splits, entropy floors, and prefix-free code tables on small hand-checkable inputs.
Estimating compressibility
Use the frequency table, entropy, and savings percent under the 8-bit baseline to judge whether a payload is worth entropy-coding.
Debugging symbol distributions
Expose skewed versus uniform frequency tables, deterministic tie-breaks, and code-point handling of emoji before wiring data into a real codec.
Common mistakes
Mistake:Reading savingsPercent as a real file-size guarantee.
Fix:The baseline is always length × 8 bits with no tree-storage or byte-alignment overhead. Treat it as a comparative estimate, not a DEFLATE output size.
Mistake:Expecting Shannon-Fano to beat Huffman.
Fix:Huffman minimizes the weighted length; Shannon-Fano can only tie or lose (e.g. 27 vs >= 27 bits on AAAAAAABBBCCDE). Compare them to learn, then ship Huffman.
Mistake:Counting emoji or accented characters as bytes.
Fix:The analyzer counts code points, not UTF-8 bytes, so 😀😀🎉 is length 3 with two distinct symbols. Multiply by the real encoding width separately when sizing bytes.
Frequently asked questions
What does this tool do?
It counts symbol frequencies per Unicode code point in your text, builds both a Huffman tree and a Shannon-Fano tree, and reports per-symbol binary codes plus entropy, average Huffman code length, encoded bits, and savings against an 8-bits-per-symbol baseline.
Why is Shannon-Fano sometimes longer than Huffman?
Huffman always minimizes the frequency-weighted length by merging the two lowest nodes, while Shannon-Fano only splits sorted symbols near the half-total — a heuristic that can tie but never beat Huffman (e.g. 27 vs >= 27 bits on AAAAAAABBBCCDE). Single symbols get code 0 in both, and uniform inputs like abcd get equal-length 2-bit codes with entropy exactly 2.
Is my text uploaded or stored?
No. Counting, tree building, and entropy math run entirely in your browser — the analyzed text never leaves your device.
How should I use the entropy and savings figures?
Treat entropy as the theoretical floor and averageCodeLength as the achieved Huffman rate; savingsPercent compares against length × 8 bits with no tree or framing overhead, so use it to compare inputs and judge whether entropy coding is worthwhile, not as a compressed file size.
Related guides
References & standards
Related tools
.env Secret Safety Linter
Validate .env syntax and spot likely leaked credentials or placeholder secrets.
.htaccess Generator
Build an Apache .htaccess — HTTPS redirects, rewrites, error pages, security headers, and basic auth
2D Fluid Dynamics & Particle Physics Sandbox
A physics playground with two engines sharing one canvas. The fluid mode runs a real Eulerian Navier-Stokes solver — semi-Lagrangian advection, explicit diffusion, Jacobi pressure projection and vorticity confinement — that you paint with dye and velocity using mouse or touch. The particle mode is a damped Verlet N-body engine with gravity wells, Coulomb attractors and repulsors, spring links, wall restitution and elastic circle collisions. Particle counts adapt to the device (100k target on WebGL2 desktop, 2k-5k on CPU fallback), and every configuration exports as runnable code: a Matter.js world, a PixiJS ticker setup, or a standalone vanilla Canvas engine.
AI Function Calling Schema Generator
Generate function calling JSON schemas from TypeScript interfaces
Algorithm Arena & Data Structure Visualizer
Interactive arena for algorithms and data structures: eight sorting algorithms racing on one seeded input, six pathfinding algorithms walking generated mazes, and BST, AVL, Red-Black, B-tree, heap and trie operations replayed step by step with rotations highlighted. Every run shows the Big-O table and the phase-highlighted reference implementation in four languages, and compared values can be played as pitch (sonification) through the shared audio engine. Everything runs client-side; inputs never leave the browser.
Ansible Playbook Generator
Build an Ansible playbook — hosts, vars, and tasks with modules — as YAML