2

I want to encode an id to unique strings containing numbers and uppercase letters, like this:

40 => A5TY8

but

41 => Y7HEG

Where the output for 41 is completely different from 40's A5TY9.

How to do this?

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
mitch
  • 2,235
  • 3
  • 27
  • 46

1 Answers1

3

I wanted to tell you all about digests.. but seeing your comment I think you want something like this

https://github.com/namick/obfuscate_id

or better yet a more generic

https://github.com/patdeegan/integer-obfuscator

you can also encode it with Base64 which is reverisble

http://ruby-doc.org/stdlib-1.9.3/libdoc/base64/rdoc/Base64.html

note that you might want to use urlsafe_encode64 so you won't have /n and stuff in there

so you can do something like

require "base64"

original = 41

converted = Base64.urlsafe_encode64("41")
converted_for_display = converted.tr('^A-Za-z0-9', '')
# => "NDE"

reversed = Base64.urlsafe_decode64(converted)

you can also encrypt the number which should make it unique and reversible, but slower and with more hassle but you can pick whatever key you want

Nick Ginanto
  • 31,090
  • 47
  • 134
  • 244
  • Thank you, but solution numbers with base are similar, NDE, NDA. The most interesting is using integer-obfuscator and then use base. – mitch Jan 21 '13 at 18:50
  • ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".split("").shuffle.join def bijective_encode(i) return ALPHABET[0] if i == 0 s = '' base = ALPHABET.length while i > 0 s << ALPHABET[i.modulo(base)] i /= base end s.reverse end def bijective_decode(s) i = 0 base = ALPHABET.length s.each_char { |c| i = i * base + ALPHABET.index(c) } i end $salt = 1369136 def decode(id) (bijective_decode(id) >> 18) - $salt end def encode(id) bijective_encode((id+$salt) << 18) end I can't "Answer your question" but this is the best solution for me. – mitch Jan 24 '13 at 10:47