Rust Convert String to Base64
In this tutorial, we will learn how to convert a string to Base64 and back to a string in Rust using the base64 crate. Base64 is a widely used method for encoding binary data as ASCII characters.
Installing the base64 Crate
To get started, add the following dependency to your Cargo.toml file:
base64 = "0.13.0"
Encoding a String to Base64
To encode a string as Base64, import the base64 crate and use the encode() function. Here's an example:
use base64;
fn main() {
let original_string = "This is a test string";
let encoded_string = base64::encode(original_string);
println!("Encoded string: {}", encoded_string);
}
Decoding a Base64 String
To decode a Base64 string back to its original string representation, use the decode() function. Here's an example:
use base64;
use std::str;
fn main() {
let encoded_string = "VGhpcyBpcyBhIHRlc3Qgc3RyaW5n";
let decoded_bytes = base64::decode(encoded_string).unwrap();
let decoded_string = str::from_utf8(&decoded_bytes).unwrap();
println!("Decoded string: {}", decoded_string);
}