You can use the {:b} formatting string to convert numbers to binary strings. For example, format!("{:b}", 'C' as u32) returns "1000011".
Then it should be a simple matter of looping over the chars or bytes of the string, looking for sequences of 0s and 1s, and printing the appropriate number of 0s and spaces for each sequence.
That is correct. format!() will format the input as a string in memory, while print!() (and it's bigger brother, println!()) will perform the formatting and then print it out.
It will help a lot if you provide very specific questions about what parts of the code you are having problems understanding, including exact copies of any error messages you are asking about. Also, please read through the Rust book and the str documentation to learn the basics of programming and string handling in Rust.
It sounds like you want to treat a string as a series of bytes, and encode each byte in your special binary notation. From your previous comment, you know how to loop over each byte of a string. If you want to print each byte in your encoding, then you just need a function that takes a single byte and encodes it:
fn encode(byte: u8) -> String {
// ...
}
for byte in message.bytes() {
let encoded = encode(byte);
println!("{}", encoded);
}
To write the encode function, see my first comment. Begin by using format! to convert the byte to a binary string, then loop through that string looking for runs of zeros or ones. You'll need to keep track of how much of the string you have already encoded, and stop when you reach the end:
fn encode(byte: u8) -> String {
// Convert the number into a binary string.
let binary = format!("{:b}", byte).into_bytes();
let mut result = String::new();
let mut start = 0;
while start < binary.len() {
// Check if the next byte is b'0' or b'1'.
let b = binary[start];
result.push_str(if b == b'1' { "0 " } else { "00 " });
// See how many bytes in a row are the same.
let count = binary[start..].iter().take_while(|x| **x == b).count();
result.push_str(&"0".repeat(count));
result.push(' ');
// Next time, skip all the bytes we've already encoded.
start += count;
}
result
}
There are also more efficient ways to do this using bitwise operators instead of converting to a string, but this way is a little simpler to explain and probably fast enough for most purposes.
Oh i tried with to_bytes() earlier, but as_bytes() works great, Ok Solved by @mbrubeck@Yandros
Thank you guys! And rust is the future ! I am having some hard times learning rust as my first programming language,but nothing is impossible and i want to much to learn this language! Thank you all for your responses