ruby - Convert integer to base 26, using a to z as digits -


i need implement decimal chars converter. have 26 chars available, it's converting integer base 26 system , then, changing each number it's alphabet counterpart. i don't want use characters 0-9 in final result string. can use to_s() method , how goes:

82.to_s(26)  #=> "34" / gives me "de" 120.to_s(26)  #=> "4g" / should give me "aep", it's not 

ruby to_s() method returns value in format not helpful. number 82 converted fine, conversion of 120 returns value have no idea how handle.

could explain how can make 120 convertion (as example) return aep equivalent? in other words, how convert decimal base 26 without using numbers in output?

ruby's fixnum#to_s( base ) , string#to_i( base ) representing numbers in different bases. cannot use arbitrary characters them though, designed compatible conventions hex , base64 amongst other things.

if not converting different base, encoding decimal digits letters , back, simple substitution needed:

46.to_s.tr( "0123456789", "abcdefghijk" ) => "eg"  "eg".tr( "abcdefghijk", "0123456789" ).to_i => 46 

so, if want both, , use a-z represent number in base 26:

46.to_s(26).tr( "0123456789abcdefghijklmnopq", "abcdefghijklmnopqrstuvwxyz" ) => "bu"  "bu".tr( "abcdefghijklmnopqrstuvwxyz", "0123456789abcdefghijklmnopq" ).to_i(26) => 46 

Comments

Popular posts from this blog

html5 - What is breaking my page when printing? -

c# - must be a non-abstract type with a public parameterless constructor in redis -

ajax - PHP/JSON Login script (Twitter style) not setting sessions -