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;
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
write!(name_in_binary, "{character:b}").unwrap().There's no such thing as a binary string in Rust. There's byte strings, which are a special literal used to create arrays of u8; they are indistinguishable from other arrays of u8.
When you do manipulation of arrays of u8, you want to work with Vec<u8>, not arrays. If you want to convert a String or str to an array of u8, you get a slice using as_bytes. If you want to get a Vec<u8> from a String, you can use into_bytes instead.
A binary string in Rust is an array of u8
let binary_string: &[u8; 3] = b"abc";
to convert a string slice to a binary string use as_bytes()
let string = "abc";
let binary_string = string.as_bytes(); // = [97, 98, 99]
same for String:
let string = String::from("abc");
let binary_string = string.as_bytes(); // = [97, 98, 99]
to have a vector instead of an array add to_vec() in the end
let string = "abc";
let binary_string = string.as_bytes().to_vec(); // = vec![97, 98, 99]
This was my solution.
In order to accommodate for the utf-8 format spec, each byte should be left padded up to 8 bits with 0.
The accepted answer's `format!("0{:b}")` does not take into consideration for characters above number 128 which did not work for me since I wasn't just working with ASCII letters.
fn main() {
let chars = "日本語 ENG €";
let mut chars_in_binary = String::from("");
for char in chars.as_bytes() {
chars_in_binary += &format!("{char:0>8b} ");
}
println!("The binary representation of the following utf8 string\n \"{chars}\"\nis\n {chars_in_binary}");
}