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;
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().
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();
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With