Reputation: 375
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;
Upvotes: 10
Views: 21049
Reputation: 2114
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]
Upvotes: 0
Reputation: 11
I find this solution using Iterator.
let bits: String = txt.into_bytes()
.iter()
.map(|&c| format!("{c:08b}"))
.collect();
Upvotes: 0
Reputation: 141
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
Upvotes: 14
Reputation: 71899
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.
Upvotes: 9