Is there anything in Rust to convert a binary string to an integer?

若如初见. 提交于 2019-12-23 09:32:43

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!