Skip to content

Instantly share code, notes, and snippets.

@naoto0822
Created February 2, 2022 01:05
Show Gist options
  • Save naoto0822/a61ef5a0a2c3d1dc1b23166f4954538c to your computer and use it in GitHub Desktop.
Save naoto0822/a61ef5a0a2c3d1dc1b23166f4954538c to your computer and use it in GitHub Desktop.
use serde::{Deserialize, Serialize};
use std::fs::File;
use std::io::BufReader;
use std::collections::HashMap;
fn main() {
println!("Hello, world!");
let input = "naoto".to_string();
println!("input: {:?}", input);
// 1 Input value is converted to binary values.
let mut binary = "".to_string();
for c in input.clone().into_bytes() {
binary += &format!("{:08b}", c);
}
println!("binary: {}", binary);
// 2 binary value is split by each 6 bit.
let length = if binary.len() % 6 == 0 {
binary.len() / 6
} else {
binary.len() / 6 + 1
};
let mut six_bits: Vec<String> = vec!["".to_string(); length];
for (i, c) in binary.as_str().chars().enumerate() {
let mut idx = (i+1) / 6;
if (i+1) % 6 == 0 {
idx-=1;
six_bits[idx].push(c);
} else {
six_bits[idx].push(c);
}
}
println!("{:?}", six_bits);
// 3 If last value is shorter than 6 bit, last value filled 0
if let Some(last) = six_bits.last_mut() {
let rem = last.len() % 6;
if rem != 0 {
let len = 6 - rem;
let fills: Vec<String> = vec!["0".to_string(); len];
*last = format!("{}{}", last, fills.join(""));
}
}
println!("{:?}", six_bits);
// 4 6 bits is converted every 4 char (24 bit) from Base64 Table.
// - using serde_json
// - base64_encode_table.json
// {"110000": "w", "110001": "x"....}
type Table = HashMap<String, String>;
let file_name = "./base64_encode_table.json";
let file = File::open(file_name).unwrap();
let reader = BufReader::new(file);
let base64_table: Table = serde_json::from_reader(reader).unwrap();
// converting
let mut encoded = "".to_string();
for (i, c) in six_bits.iter().enumerate() {
if let Some(v) = base64_table.get(c) {
encoded += v;
}
}
println!{"{}", encoded};
// 5 if converted string short 24 bit, last encoding block added padding char (=).
let rem = encoded.len() % 4;
if rem != 0 {
let len = 4 - rem;
let fills: Vec<String> = vec!["=".to_string(); len];
let joins = fills.join("");
encoded += &joins;
}
println!{"{}", encoded};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment