Skip to content

Instantly share code, notes, and snippets.

@sdkfz181tiger
Last active April 9, 2024 02:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sdkfz181tiger/2630463ce97c2d914bce406f1c054afd to your computer and use it in GitHub Desktop.
Save sdkfz181tiger/2630463ce97c2d914bce406f1c054afd to your computer and use it in GitHub Desktop.
基数変換で遊んでみよう_その2_Base64変換
# coding: utf-8
import base64
# Base64変換表
BASE64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
# ASCII符号表(コンピュータ概論:p46)
ASCII = [[], [],
["SP", "!", "\"", "#", "$", "%", "&", "'", "(", ")", "*", "+", ",", "-", ".", "/"],
["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", ":", ";", "<", "=", ">", "?"],
["@", "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", "{", "|", "}", "~", "DEL"]
]
def main():
print("main.py!!")
msg = "HELLO"
# 文字列 "HELLO" -> ASCII
# -> 0100100001000101010011000100110001001111
bin_ascii = "".join(str2ascii(msg))
# 6文字(bit)区切りに分割
bin_arr = [bin_ascii[x:x+6] for x in range(0, len(bin_ascii), 6)]
# 6文字(bit)区切りに調整する(足りない場合は"0"で埋める)
bin_last = len(bin_arr) - 1
if len(bin_arr[bin_last]) < 6:
bin_arr[bin_last] = bin_arr[bin_last].ljust(6, "0")
# 2進数 -> Base64
for i in range(len(bin_arr)):
bin_arr[i] = BASE64[int(bin_arr[i], 2)]
# 4文字区切りに調整する(足りない場合は"="で埋める)
odd = len(bin_arr) % 4
if 0 < odd:
for i in range(4-odd): bin_arr.append("=")
# Base64エンコード
# Base64: HELLO -> SEVMTE8=
encoded = "".join(bin_arr)
print("Base64:", msg, "->", encoded)
# Base64デコード(検証)
# Check: b'HELLO'
decoded = base64.b64decode(encoded.encode())
print("Check:", decoded)
def str2ascii(s):
result = []
for c in s:
i, j = char2ascii(c)
result.append(d2b(i) + d2b(j))
return result
def char2ascii(c):
for i in range(len(ASCII)):
for j in range(len(ASCII[i])):
if c == ASCII[i][j]: return i, j
def d2b(d): return bin(d)[2:].zfill(4)
def d2h(d): return hex(d)[2:].zfill(1)
def b2d(b): return int(b, 2)
def h2b(h): return int(h, 16)
if __name__ == "__main__":
main()
"use strict";
// Base64変換表
const BASE64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
// ASCII符号表(コンピュータ概論:p46)
const ASCII = [[], [],
["SP", "!", "\"", "#", "$", "%", "&", "'", "(", ")", "*", "+", ",", "-", ".", "/"],
["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", ":", ";", "<", "=", ">", "?"],
["@", "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", "{", "|", "}", "~", "DEL"]
];
$(document).ready(()=>{
console.log("Ready!!");
const msg = "HELLO";
// 文字列 "HELLO" -> ASCII
// -> 0100100001000101010011000100110001001111
const ascii = str2ascii(msg).join("");
console.log("BIN:", msg, "->", ascii);
// 6文字(bit)区切りに分割
const arr = [];
for(let i=0; i<ascii.length; i+=6) arr.push(ascii.slice(i, i+6));
// 6文字(bit)区切りに調整する(足りない場合は"0"で埋める)
const last = arr.length - 1;
if(arr[last].length < 6) arr[last] = arr[last].padEnd(6, "0");
// 2進数 -> Base64
for(let i=0; i<arr.length; i++){
arr[i] = BASE64[b2d(arr[i])];
}
// 4文字区切りに調整する(足りない場合は"="で埋める)
const odd = arr.length % 4;
if(0 < odd){
for(let i=0; i<4-odd; i++) arr.push("=");
}
// Base64エンコード
// Base64: HELLO -> SEVMTE8=
const encoded = arr.join("");
console.log("Base64:", msg, "->", encoded);
// Base64デコード(検証)
// Check: HELLO
const decoded = decodeURIComponent(atob(encoded));
console.log("Check:", decoded)
});
const str2ascii = str=>{
let result = [];
for(let s of str){
const [i, j] = char2ascii(s);
result.push(d2b(i) + d2b(j));// Decimal -> Binary
}
return result;
}
const char2ascii = c=>{
for(let i=0; i<ASCII.length; i++){
for(let j=0; j<ASCII[i].length; j++){
if(c == ASCII[i][j]) return [i, j];
}
}
}
const bin2dec = bin=>{
let result = [];
for(let b of bin) result.push(b2d(b));
return result;
}
const dec2str = dec=>{
let result = [];
for(let d of dec) result.push(String.fromCharCode(d));
return result.join("");
}
const d2b = d=>d.toString(2).padStart(4, "0");
const d2h = d=>d.toString(16).padStart(1, "0");
const b2d = b=>parseInt(b, 2);
const h2b = h=>parseInt(h, 16);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment