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

北战南征 提交于 2019-12-12 13:21:47

问题


I need to implement a decimal to chars converter. I have 26 chars available, so it's about converting an integer to base 26 system and then, changing each number to it's alphabet counterpart. I don't want to use the characters 0-9 in the final result string. I can use to_s() method and this is how it goes:

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

Ruby to_s() method returns a value in a format that is not helpful. Number 82 is converted fine, but conversion of 120 returns a value I have no idea how to handle.

Could anyone explain how I can make the 120 convertion (as an example) return aep equivalent? In other words, how to convert from decimal base to 26 but without using numbers in output?


回答1:


Ruby's Fixnum#to_s( base ) and String#to_i( base ) are for representing numbers in different bases. You cannot use arbitrary characters with them though, they are designed to be compatible with conventions for hex and base64 amongst other things.

If you were not converting to a different base, but simply encoding decimal digits as letters and back, then a simple substitution would be all you needed:

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

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

So, if you want to do both, and use a-z to represent your number in base 26:

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

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


来源:https://stackoverflow.com/questions/17785420/convert-integer-to-base-26-using-a-to-z-as-digits

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!