How to encode and decode any string into Base‑36 in Ruby

1 Answer

0 votes
#!/usr/bin/env ruby

#
# Base‑36 encoding/decoding in Ruby
# -------------------------------------------
# Ruby's Integer is arbitrary‑precision, so the implementation is clean.
#

BASE36_DIGITS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ".freeze

def encode_to_base36(text)
  bytes = text.bytes
  n = 0
  bytes.each { |b| n = n * 256 + b }
  n.to_s(36).upcase
end

def decode_from_base36(encoded)
  encoded = encoded.upcase
  n = encoded.chars.reduce(0) { |acc, c| acc * 36 + BASE36_DIGITS.index(c) }

  bytes = []
  while n > 0
    bytes << (n % 256)
    n /= 256
  end

  bytes.reverse.pack("C*")
end

text    = "Hello Universe!"
encoded = encode_to_base36(text)
decoded = decode_from_base36(encoded)

puts "Original: #{text}"
puts "Base-36 encoded: #{encoded}"
puts "Decoded: #{decoded}"

__END__



=begin
run:

Original: Hello Universe!
Base-36 encoded: LP4N024HJ1YVBVD84Y8TYQP
Decoded: Hello Universe!

=end

 



answered 3 days ago by avibootz
...