Parse Hex And Binary With Radix

from_str_radix parses integers in bases 2 through 36 and to_digit converts single characters, returning typed errors when a digit is invalid for the radix.

RustData Integrity

Code

rustsnippet
15 lines
fn main() {
    // from_str_radix:按指定进制解析整数字符串,进制范围 2..=36
    println!("0xff = {:?}", u32::from_str_radix("ff", 16));
    println!("0b1010 = {:?}", u32::from_str_radix("1010", 2));

    // g 不是合法十六进制数字:返回类型化 ParseIntError,而不是静默截断
    println!("'1g' base 16 rejected: {:?}", u32::from_str_radix("1g", 16).is_err());

    // char::to_digit 把单个字符按进制转成数字;char::from_digit 反向生成字符
    println!("'a' -> {:?}", 'a'.to_digit(16));
    println!("11 -> {:?}", char::from_digit(11, 16));

    // 进制越界(如 1)会 panic:运行时契约,编译期无法发现
    println!("base 36 'zz' = {:?}", u32::from_str_radix("zz", 36));
}

What the code does

Parse Hex And Binary With Radix keeps everything in the function main.

Applying it

Running the file prints labeled results such as 0xff =, 0b1010 =, '1g' base 16 rejected: — each operation’s effect is visible in the output.

Interactive Tools for This Topic

FAQ

What does Parse Hex And Binary With Radix print when run?
No setup needed: run the file and look for labeled lines like `0xff =`, `0b1010 =`, `'1g' base 16 rejected:` in the output.