32

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.

0

3 Answers 3

69

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)

Sign up to request clarification or add additional context in comments.

Comments

2

As an alternative you can use:

let bstr = "11010101";
let i = i32::from_str_radix(bstr, 2).expect("Not a binary number!");
println!("{i}");

Which should print 213.

EDIT: Posted that answer as I thought isize for some reason was not available in my embedded rust project. Was just a typo though...

Comments

0

I made a function up by myself, and it works!

fn binary_to_u32(s: String) -> u32 {
let mut binary_digit =  s.chars().count();
let mut real_num: u32 = 0;
for c in s.chars() { 
    let mut temp_var = 2u32.pow(binary_digit.try_into().unwrap());
    temp_var /= 2;
    if c == '1'{
        real_num += temp_var;
    }
    binary_digit -= 1;
}
return real_num; }

Also, if you have need for any other integer size, just change u32 to anything you like with some replace shortcut in your text editor.

5 Comments

Why would you use this instead of the one in the standard library that is thoroughly tested?
1. It suits all integer type in rust 2. I thought it is easier to write this simple function myself than look for thing that could be non-existing.
It suits all integer typeas does the existing answer.
I did not knew that. Thank you! Maybe I am bad at Google-ing because I did not find it.
also this version has suboptimal performance with pow and division in a loop. Instead multiplication and addition would be much better.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.