Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 817
leshow Avatar asked Dec 22 '14 16:12

leshow


People also ask

How do you convert a string to a binary number?

To convert a string to binary, we first append the string's individual ASCII values to a list ( l ) using the ord(_string) function. This function gives the ASCII value of the string (i.e., ord(H) = 72 , ord(e) = 101). Then, from the list of ASCII values we can convert them to binary using bin(_integer) .

How do you convert string to rust?

To convert any type to a String is as simple as implementing the ToString trait for the type. Rather than doing so directly, you should implement the fmt::Display trait which automagically provides ToString and also allows printing the type as discussed in the section on print! .

How do you convert an integer to a binary string in Python?

To convert int to binary in Python, use the bin() method. The bin() is a built-in Python method that converts a decimal to a binary data type. The bin() function accepts a number as an argument and returns its equivalent binary string prefixed with “0b”.

Does Python convert binary?

In Python, you can simply use the bin() function to convert from a decimal value to its corresponding binary value. And similarly, the int() function to convert a binary to its decimal value. The int() function takes as second argument the base of the number to be converted, which is 2 in case of binary numbers.


1 Answers

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)

like image 109
oli_obk Avatar answered Oct 23 '22 07:10

oli_obk