Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert string to binary string in Rust?

Tags:

rust

I have a string and I want to convert it to a binary string.

let content = request_version.to_string() + &request_length.to_string() + request_json;
like image 523
Leviathan Avatar asked Feb 15 '16 08:02

Leviathan


People also ask

How do you convert a string to a number in Rust?

To convert a string to an integer in Rust, use parse() function. The parse function needs to know what type, which can be specified on the left-side of assignment like so: let str = "123"; let num: i32 = str. parse().

How do you convert string to bytes in Rust?

Here are a few different conversions between types. &str to &[u8] : let my_string: &str = "some string"; let my_bytes: &[u8] = my_string. as_bytes();

How do you convert binary to decimal in Rust?

Rust Conversion binary number to a decimal integer Now in Rust, you can add the prefix 0b to represent a binary number, for example, “0b10110101” is a binary number for the Rust compiler. Once we assign this number to a variable num and during this assignment we are specifying the type of num as i32.


1 Answers

You probably meant a binary representation of your string in the type String.

fn main() {
    let name = "Jake".to_string();
    let mut name_in_binary = "".to_string();

    // Call into_bytes() which returns a Vec<u8>, and iterate accordingly
    // I only called clone() because this for loop takes ownership
    for character in name.clone().into_bytes() {
        name_in_binary += &format!("0{:b} ", character);
    }
    println!("\"{}\" in binary is {}", name, name_in_binary);
}

And that results:

"Jake" in binary is 01001010 01100001 01101011 01100101
like image 150
Senre Dynacity Avatar answered Sep 19 '22 08:09

Senre Dynacity