目前,我正在使用以下代码将数字作为二进制(基数 2)、八进制(基数 8)或十六进制(基数 16)字符串返回。
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
)),
}
}
现在我想替换内部的 match
语句,这样我就可以将数字作为任意基数的字符串(例如基数 3)返回。是否有任何内置函数可以将数字转换为任何给定的基数,类似于 JavaScript 的 Number.toString()
method ?
最佳答案
目前,you cannot do it using the standard library , 但您可以:
- 使用我的箱子
radix_fmt
或推出您自己的实现:
fn format_radix(mut x: u32, radix: u32) -> String { let mut result = vec![]; loop { let m = x % radix; x = x / radix; // will panic if you use a bad radix (< 2 or > 36). result.push(std::char::from_digit(m, radix).unwrap()); if x == 0 { break; } } result.into_iter().rev().collect() } fn main() { assert_eq!(format_radix(1234, 10), "1234"); assert_eq!(format_radix(1000, 10), "1000"); assert_eq!(format_radix(0, 10), "0"); }
关于rust - 将数字格式化/转换为任何基数的字符串(包括十进制或十六进制以外的基数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48893989/