使用a到z作为数字将整数转换为以26为底的整数 [英] Convert integer to base 26, using a to z as digits

查看:154
本文介绍了使用a到z作为数字将整数转换为以26为底的整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要实现一个小数到字符转换器.我有26个字符,所以这是关于将整数转换为以26为基数的系统,然后将每个数字更改为其对应的字母. 我不想在最终结果字符串中使用字符0-9..我可以使用to_s()方法,它是这样的:

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()方法以无用的格式返回值.数字82可以很好地转换,但是转换为120会返回一个我不知道如何处理的值.

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.

任何人都可以解释我如何使120转换(例如)返回等效的aep吗?换句话说,如何在不使用数字的情况下从十进制基数转换为26?

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?

推荐答案

Ruby的Fixnum#to_s( base )String#to_i( base )用于表示不同基数的数字.但是,您不能将任意字符与它们一起使用,它们被设计为与十六进制和base64的约定兼容.

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

因此,如果您想同时进行 ,并使用a-z表示以26为底的数字:

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

这篇关于使用a到z作为数字将整数转换为以26为底的整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆