Skip to content

QR Code Generator — Rust source

Turn any text or URL into a downloadable QR code. Full ISO encoder with all error-correction levels, versions 1-40, SVG and PNG export, colors and quiet-zone control — runs entirely in your browser.

This is the Rust implementation — the same logic the interactive tool runs, in a shareable, citable form.

//! qr-code-generator — QR format information (BCH).
//!
//! Display snippet: assembling the module matrix is too long to show
//! here; this ports `format_info_bch(data5)` from the TypeScript lib
//! (src/lib/qr.ts). The full encoder (modes, Reed-Solomon EC, masking,
//! matrix) lives in the TypeScript/Go sources.
//!
//! The 15-bit format string protects 5 data bits — 2 error-correction
//! level bits (L=01 M=00 Q=11 H=10) followed by the 3-bit mask pattern —
//! with a BCH(15,5) code using generator 0x537, then XORs the result with
//! the fixed 0x5412 pattern so an all-zero string is never valid.

/// Error-correction level indicator bits (ISO/IEC 18004 table C.1).
fn ec_format_bits(ec_level: char) -> Option<u16> {
    match ec_level {
        'L' => Some(0b01),
        'M' => Some(0b00),
        'Q' => Some(0b11),
        'H' => Some(0b10),
        _ => None,
    }
}

/// 15-bit format info string (MSB first) for (ec_level, mask).
pub fn format_info(ec_level: char, mask: u16) -> Option<String> {
    Some(format_info_bch((ec_format_bits(ec_level)? << 3) | mask))
}

/// 15-bit format info string (MSB first) for a 5-bit data value.
pub fn format_info_bch(data5: u16) -> String {
    let mut v = data5 << 10;
    const G: u16 = 0x537; // BCH(15,5) generator polynomial
    let mut i = 14;
    while i >= 10 {
        if v & (1 << i) != 0 {
            v ^= G << (i - 10); // polynomial long division
        }
        i -= 1;
    }
    let full = ((data5 << 10) | (v & 0x3ff)) ^ 0x5412; // apply the mask pattern
    format!("{full:015b}")
}

// Example:
//   format_info('L', 0) -> "111011111000100" (0x77C4, matching the published tables)

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →