Skip to content

Instantly share code, notes, and snippets.

@xixilive
Created April 28, 2012 10:40
Show Gist options
  • Save xixilive/2517860 to your computer and use it in GitHub Desktop.
Save xixilive/2517860 to your computer and use it in GitHub Desktop.
Base32 string encoder, generate a unique shorten string from a long string, such as a url
require 'digest/md5'
module Shorten
#base32
TABLE = %w(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 2 3 4 6 7 8)
# short('balabala') => Array
# short('balabala',1) => String, Array[1]
def self.short long_str, index = nil
index = (0..3).to_a.include?(index) ? index : nil
hash_string = Digest::MD5.hexdigest(long_str)
hashes,strs = [],[]
hashes = (0..31).step(8).collect{|i|hash_string[i,8]}
strs = hashes.collect do |str|
i = 0x3FFFFFFF & "0x#{str}".hex
str =''
(0..5).each do
j = 0x0000001F & i
str << TABLE[j]
i = i >> 5
end
str
end
index.nil? ? strs : strs[index]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment