LoginSignup
3
2

More than 5 years have passed since last update.

RubyでBase64エンコード

Last updated at Posted at 2017-06-04

RubyでBase64

参考 http://qiita.com/PlanetMeron/items/2905e2d0aa7fe46a36d4
base64_table.jsonをこちらから借ります

まずコマンドライン引数から文字列をとってきてバイナリに変換します

biarray = []

ARGV.each_with_index do |arg, i|
  biarray << arg.unpack("B*")
end

string = biarray.join

その配列をjoinさせて一つの文字列にし、6文字ごとに分割します
最後に二桁余るので0をつけます

binary_strings = string.scan(/.{1,6}/)

binary_strings[-1] += "0000"

最後にbase64変換表と照らし合わせ変換していきます
image.png

https://gist.github.com/wakusei-meron-/d292193e35fb844c19c9
base64_table.jsonをこちらから借ります

file = open('base64_table.json', "r")
dictionary = JSON.load(file)
result = ""
binary_strings.each do |string|
  result += dictionary[string]
end

puts result

これで完成です!

最終的なプログラム

require 'json'

biarray = []

ARGV.each do |arg|
  biarray << arg.unpack("B*")
end

string = biarray.join

binary_strings = string.scan(/.{1,6}/)

binary_strings[-1] += "0000"

file = open('base64_table.json', "r")
dictionary = JSON.load(file)
result = ""
binary_strings.each do |string|
  result += dictionary[string]
end

puts result

3
2
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
3
2