Non-decimal radices/Convert: Difference between revisions
Content added Content deleted
(Add source for Rust) |
(Reduce the Rust code) |
||
Line 2,847: | Line 2,847: | ||
=={{header|Rust}}== |
=={{header|Rust}}== |
||
Rust standard library provides parsing a string in a given radix to all integer types. |
|||
There is no reverse operation (except for format specifiers for binary, octal, decimal |
|||
and hexadecimal base). |
|||
<lang Rust>fn format_with_radix(mut n: u32, radix: u32) -> String { |
<lang Rust>fn format_with_radix(mut n: u32, radix: u32) -> String { |
||
assert!(2 <= radix && radix <= 36); |
assert!(2 <= radix && radix <= 36); |
||
Line 2,861: | Line 2,865: | ||
result.chars().rev().collect() |
result.chars().rev().collect() |
||
} |
|||
fn parse_with_radix<S: AsRef<str>>(s: S, radix: u32) -> Result<u32, S> { |
|||
assert!(2 <= radix && radix <= 36); |
|||
let mut result = 0; |
|||
for digit in s.as_ref().chars().map(|it| it.to_digit(radix)) { |
|||
match digit { |
|||
Some(value) => result = result * radix + value, |
|||
None => return Err(s), |
|||
} |
|||
} |
|||
Ok(result) |
|||
} |
} |
||
Line 2,883: | Line 2,873: | ||
for radix in 2..=36 { |
for radix in 2..=36 { |
||
let s = format_with_radix(value, radix); |
let s = format_with_radix(value, radix); |
||
let v = |
let v = u32::from_str_radix(s.as_str(), radix).unwrap(); |
||
assert_eq!(value, v); |
assert_eq!(value, v); |
||
} |
} |
||
Line 2,893: | Line 2,883: | ||
println!("{}", format_with_radix(0xdeadbeef, 36)); |
println!("{}", format_with_radix(0xdeadbeef, 36)); |
||
println!("{}", format_with_radix(0xdeadbeef, 16)); |
println!("{}", format_with_radix(0xdeadbeef, 16)); |
||
println!("{}", |
println!("{}", u32::from_str_radix("DeadBeef", 16)?); |
||
Ok(()) |
Ok(()) |
||
}</lang> |
}</lang> |