Posted By

gusto on 12/06/06


Tagged

decimal conversion


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

lenn0x


Decimal to Base 36 / Base 36 to Decimal


 / Published in: Other
 

  1. DIGITS = ('0'..'9').to_a + ('A'..'Z').to_a
  2.  
  3. def to_base36_from_l(num)
  4. result = ""
  5. while num != 0
  6. tmp = num / DIGITS.length
  7. remainder = num - tmp * DIGITS.length
  8. char = DIGITS[remainder]
  9. num = tmp
  10. result = char + result
  11. end
  12. result
  13. end
  14.  
  15. def to_l_from_base36(str)
  16. answer = 0
  17. str.reverse.split("").each_with_index { |c, i|
  18. answer += (DIGITS.index(c) * (DIGITS.length ** i))
  19. }
  20. answer
  21. end
  22.  
  23. # sample usage
  24.  
  25. num = 1451252361345125
  26.  
  27. base36 = to_base36_from_l(num)
  28. puts "#{base36} from #{to_l_from_base36(base36)}"
  29.  
  30. # output: EAFC4PPW85 from 1451252361345125

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: lenn0x on December 6, 2006

test

You need to login to post a comment.