Skip to content

Instantly share code, notes, and snippets.

@saurabhnanda
Created August 3, 2012 05:43
Show Gist options
  • Save saurabhnanda/3244786 to your computer and use it in GitHub Desktop.
Save saurabhnanda/3244786 to your computer and use it in GitHub Desktop.
class Base64
##
def self.convert_to_char(n)
if (0..25).cover?(n)
return (65 + n).chr
elsif (26..51).cover?(n)
return (97 + n - 26).chr
elsif (52..61).cover?(n)
return (n - 52).to_s
elsif n==62
return '+'
elsif n==63
return '-'
else
raise 'Unknown index'
end
end
##
def self.convert_24_bits(s)
first = (s[0].ord & 252) >> 2
second = ((s[0].ord & 3) << 4) | (s[1].ord >> 4)
third = ((s[1].ord & 15) << 2) | (s[2].ord >> 6)
fourth = s[2].ord & 63
[first, second, third, fourth].collect {|x| self.convert_to_char(x)}.join('')
end
##
def self.encode(s)
padding = 0
if (s.length % 3 == 1)
s += 0.chr + 0.chr
padding = 2
elsif (s.length % 3 == 2)
s += 0.chr
padding = 1
end
output = ''
(0..s.length-1).step(3) do |i|
slice = s[i..(i+2)]
output += self.convert_24_bits(slice)
end
if padding == 1
output[-1] = "="
elsif padding == 2
output[-1] = "="
output[-2] = "="
end
return output
end
end
test_string = "12345678"
encoded = Base64.encode(test_string)
decoded = Base64.decode(encoded)
if decoded == test_string
puts "Pass"
else
puts "Fail"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment