A
Aaron D. Gifford
Yes, there's always:
require 'base64'
Base64::encoe64(data)
But now and then it's fun to write one's own base64 encoder just for
the fun of it.
What I want to ask is this: How short can one get a function
definition that takes a string as input and returns a base-64
(MIME64-style, except for NO newlines/linefeeds--output is all one
giant line of encoded text in the character set 'A' to 'Z', 'a' to
'z', '0' to '9', '+', and '/')?
The shortest I've got it down to is 276 characters. WARNING: My email
client is gonna line-break this and mess it up. Just remove the
whitespace.)
def e(s);c=('A'..'Z').to_a.join+('a'..'z').to_a.join+'0123456789+/';(t=s.unpack('C*').inject([0,'',0]){|a,v|a[0]==0?[2,a[1]+c[v>>2,1],v*16&48]:a[0]==2?[4,a[1]+c[v>>4|a[2],1],v*4&60]:[0,a[1]+c[v>>6|a[2],1]+c[v&63,
1],0]})[1]+(t[0]==0?'':t[0]==2?c[t[2],1]+'==':c[t[2],1]+'=');end
If the above is too corrupted, I stuck it on my personal web site:
http://www.aarongifford.com/base64.rb.txt
The 276-character encoder works in Ruby 1.9.1 and Ruby 1.8.7 and
super-simplistic tests comparing results against the Base64 encoder
appear to work (as long as you strip out line breaks Base64 includes).
I'd love to hear suggestions to squeeze a few more characters out of it.
Ideas? Suggestions?
Having a bit too much fun fiddling with Ruby,
Aaron out.
require 'base64'
Base64::encoe64(data)
But now and then it's fun to write one's own base64 encoder just for
the fun of it.
What I want to ask is this: How short can one get a function
definition that takes a string as input and returns a base-64
(MIME64-style, except for NO newlines/linefeeds--output is all one
giant line of encoded text in the character set 'A' to 'Z', 'a' to
'z', '0' to '9', '+', and '/')?
The shortest I've got it down to is 276 characters. WARNING: My email
client is gonna line-break this and mess it up. Just remove the
whitespace.)
def e(s);c=('A'..'Z').to_a.join+('a'..'z').to_a.join+'0123456789+/';(t=s.unpack('C*').inject([0,'',0]){|a,v|a[0]==0?[2,a[1]+c[v>>2,1],v*16&48]:a[0]==2?[4,a[1]+c[v>>4|a[2],1],v*4&60]:[0,a[1]+c[v>>6|a[2],1]+c[v&63,
1],0]})[1]+(t[0]==0?'':t[0]==2?c[t[2],1]+'==':c[t[2],1]+'=');end
If the above is too corrupted, I stuck it on my personal web site:
http://www.aarongifford.com/base64.rb.txt
The 276-character encoder works in Ruby 1.9.1 and Ruby 1.8.7 and
super-simplistic tests comparing results against the Base64 encoder
appear to work (as long as you strip out line breaks Base64 includes).
I'd love to hear suggestions to squeeze a few more characters out of it.
Ideas? Suggestions?
Having a bit too much fun fiddling with Ruby,
Aaron out.