0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

paiza.ioでrust その19

Posted at

概要

paiza.ioでrustやってみた。
base64見つけたので、やってみた。

参考にしたページ

サンプルコード


use std::collections::HashMap;
use std::io::{stdout, Write};

fn getline() -> String {
    let mut __ret = String::new();
    std::io::stdin().read_line(&mut __ret).ok();
    return __ret;
}

fn make_conversion_table() -> HashMap<String, String> {
    let mut conversion_table = HashMap::new();
    let values = vec!["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "+", "/"];
    for i in 0..values.len() 
    {
        let bin = format!("{:06b}", i as i32);
        conversion_table.insert(bin, values[i].to_string());
    }
    return conversion_table;
}

fn main() {
    print!("Input : ");
    stdout().flush().unwrap();
    let plain = getline().trim().to_string();
    let mut all_bits = String::new();
    for c in plain.chars().into_iter() 
    {
        let bin = format!("{:08b}", c as i32);
        all_bits += &bin;
    }
    let mut six_bits: Vec<String> = Vec::new();
    let mut six_bit = String::new();
    let mut count = 0;
    for c in all_bits.chars().into_iter() 
    {
        count += 1;
        six_bit += &c.to_string();
        if count % 6 == 0 
        {
            six_bits.push(six_bit);
            six_bit = "".to_string();
        }
    }
    if six_bit.len() > 0 
    {
        let add_zero_count = 6 - six_bit.len();
        let mut add_zero_str = String::new();
        for _ in 0..add_zero_count 
        {
            add_zero_str += "0";
        }
        six_bit += &add_zero_str;
        six_bits.push(six_bit);
    }
    let conversion_table = make_conversion_table();     
    let mut base64_str = six_bits.iter().flat_map(|six_bit| conversion_table[six_bit].chars()).collect::<String>();     
    if base64_str.len() % 4 != 0 
    {
        let mut equal_str = String::new();
        let add_equal_count = 4 - (base64_str.len() % 4);
        for _ in 0..add_equal_count 
        {
            equal_str += "=";
        }
        base64_str += &equal_str;
    }
    println!("Base64 : {}", base64_str);
}




実行結果

ABCD

Input : Base64 : QUJDRA==

成果物

以上。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?