小编Mel*_*ava的帖子

是否有内置函数将数字转换为任何基数中的字符串?

我想替换内部match语句并为字母表用尽时的所有值工作.我知道我可以自己写,但我想使用内置函数.

fn convert(inp: u32, out: u32, numb: &String) -> Result<String, String> {
    match isize::from_str_radix(numb, inp) {
        Ok(a) => match out {
            2 => Ok(format!("{:b}", a)),
            8 => Ok(format!("{:o}", a)),
            16 => Ok(format!("{:x}", a)),
            10 => Ok(format!("{}", a)),
            0 | 1 => Err(format!("No base lower than 2!")),
            _ => Err(format!("printing in this base is not supported")),
        },
        Err(e) => Err(format!(
            "Could not convert {} to a number in base {}.\n{:?}\n",
            numb, inp, e
        )),
    }
}
Run Code Online (Sandbox Code Playgroud)

format rust

6
推荐指数
2
解决办法
1144
查看次数

标签 统计

format ×1

rust ×1