Skip to content

Instantly share code, notes, and snippets.

@rsayers
Created January 13, 2014 21:09
Show Gist options
  • Select an option

  • Save rsayers/8408198 to your computer and use it in GitHub Desktop.

Select an option

Save rsayers/8408198 to your computer and use it in GitHub Desktop.
Rough implementation of Base64 done to understand it a bit better
# This doesnt handle padding or non ascii, but its a rough implementation based on the wikipedia description
module RobBase64
def self.encodebyte(byte)
case byte
when 0..25 then (byte+65).chr
when 26..51 then (byte-26+97).chr
when 52..61 then (byte-4).chr
when 62 then "+"
when 63 then "/"
else puts "Not found #{byte}"
end
end
def self.decodebyte(byte)
case byte
when "A".."Z" then byte.ord-65
when "a".."z" then byte.ord-71
when "0".."9" then byte.ord+4
when "+" then 62
when "/" then 63
end
end
def self.bits(str)
str.bytes.map { |c|
("%08d" % c.to_s(2)).split('')
}.flatten
end
def self.encode(str)
puts "Encoding #{str}"
self.bits(str).each_slice(6).map { |i|
self.encodebyte(i.join('').to_i(2))
}.join('')
end
def self.decode(str)
puts "Decoding #{str}"
str.each_char.map {|i|
"%06d" % self.decodebyte(i).to_s(2)
}.join('').split('').each_slice(8).map{ |i|
i.join('').to_i(2).chr
}.join('')
end
end
encoded = RobBase64.encode("How now brown cow.")
decoded = RobBase64.decode(encoded)
puts encoded
puts decoded
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment