问题
My binary resides as a string right now, I was hoping to format! it as an integer the same way I formatted my integer to binary: format!("{:b}", number).
I have a larger string of binary that I'm taking slices out of in a loop, so let's assume one of my slices is:
let bin_idx: &str = "01110011001";
I want to format that binary into an integer:
format!("{:i}", bin_idx);
This gives a compiler error:
error: unknown format trait `i`
--> src/main.rs:3:21
|
3 | format!("{:i}", bin_idx);
| ^^^^^^^
I also tried d and u and got the same error.
回答1:
First of all, you should be using the official docs; those you pointed to are way outdated.
You have a string and you can't format a string as an integer. I think what you want is a parser. Here's a version using from_str_radix:
fn main() {
let bin_idx = "01110011001";
let intval = isize::from_str_radix(bin_idx, 2).unwrap();
println!("{}", intval);
}
(playground)
来源:https://stackoverflow.com/questions/27606616/is-there-anything-in-rust-to-convert-a-binary-string-to-an-integer