Caesar Cipher With Char Arithmetic

Shift letters by a fixed offset using u8 arithmetic on ASCII ranges, wrapping inside each case so digits and punctuation stay untouched.

RustSecurity Boundaries

Code

snippet
fn shift(text: &str, by: i8) -> String {
    text.chars()
        .map(|c| match c {
            // 字母按大小写各自回绕,非字母原样保留
            'a'..='z' => wrap(c as u8, b'a', by),
            'A'..='Z' => wrap(c as u8, b'A', by),
            _ => c,
        })
        .collect()
}

fn wrap(byte: u8, base: u8, by: i8) -> char {
    // +26 先把负偏移折进正区间,再 %26 回绕
    let offset = ((byte - base) as i8 + by + 26) % 26;
    (base + offset as u8) as char
}

fn main() {
    let plain = "Attack at Dawn-06:00!";
    let encoded = shift(plain, 3);
    let decoded = shift(&encoded, -3);
    println!("plain:   {plain}");
    println!("encoded: {encoded}");
    println!("decoded: {decoded}");
    println!("roundtrip: {}", decoded == plain);
}

How it works

shift walks text.chars() and maps each char through a match on its range: 'a'..='z' delegates to wrap(c as u8, b'a', by), 'A'..='Z' to wrap(c as u8, b'A', by), and any other char falls into _ => c untouched — that is why Attack at Dawn-06:00! keeps its -, : and ! after encoding.

wrap does the arithmetic: byte - base normalizes the letter to 0–25, as i8 + by applies the shift, and + 26) % 26 folds negative offsets back into the positive range before % 26 wraps — so shift(&encoded, -3) decrypts by the same path that shift(plain, 3) encrypts. main asserts the round trip with decoded == plain, printing roundtrip: true.

What to watch for

  • The + 26 before % 26 is load-bearing for negative by: in Rust, -3 % 26 would stay negative and produce a wrong char.
  • shift operates on chars, not bytes, so multi-byte UTF-8 letters (é, ü) pass through _ => c unshifted rather than being mangled.
  • by: i8 keeps offsets small; a shift of 26 is the identity, and the code makes no attempt to normalize by itself.

Putting it to use

Entry signature: fn shift(text: &str, by: i8) -> String

Expect labeled output — plain:, encoded:, decoded: — when the file runs.

main calls 1 helper in sequence: shift.

Core lines

.map(|c| match c {
    // 字母按大小写各自回绕,非字母原样保留
    'a'..='z' => wrap(c as u8, b'a', by),
    'A'..='Z' => wrap(c as u8, b'A', by),
    _ => c,
})
fn wrap(byte: u8, base: u8, by: i8) -> char {
    // +26 先把负偏移折进正区间,再 %26 回绕
    let offset = ((byte - base) as i8 + by + 26) % 26;
    (base + offset as u8) as char
}

Interactive Tools for This Topic

FAQ

What does Caesar Cipher With Char Arithmetic print when run?
No setup needed: run the file and look for labeled lines like `plain:`, `encoded:`, `decoded:` in the output.