to_digit Parses Char Digits By Radix

Parse single characters into digits with to_digit under any radix, composing with iterators to read hex input without allocations.

RustData Integrity

Code

rustsnippet
19 lines
fn main() {
    // 逐字符解析十六进制:不需要先收集再 parse 整个字符串
    let hex = "0xa3f";

    let digits: Vec<u32> = hex
        .chars()
        .filter_map(|ch| ch.to_digit(16))
        .collect();

    println!("digits: {digits:?}");

    // 非十六进制字符落 None 而不是报错:可先校验再决定策略
    let bad = "1g2";
    let all_valid = bad.chars().all(|ch| ch.is_ascii_hexdigit());
    println!("all hex digits in {bad:?}: {all_valid}");

    // 进制是参数:八进制也能解析
    println!("'7' in octal: {:?}", '7'.to_digit(8));
}

How it works

to_digit Parses Char Digits By Radix comes down to the function main.

Points of care

  • Nothing is depended on: the registry and lockfile stay empty.

Putting it to use

Primary declaration, verbatim: fn main()

Labeled lines tell the story — digits:, all hex digits in, '7' in octal: — when the file runs.

Core lines

let all_valid = bad.chars().all(|ch| ch.is_ascii_hexdigit());
.filter_map(|ch| ch.to_digit(16))
.collect();
let hex = "0xa3f";

Interactive Tools for This Topic

FAQ

What does to_digit Parses Char Digits By Radix print when run?
Execute the whole file; each printed line is prefixed with a label like `digits:`, `all hex digits in`, `'7' in octal:`.