我查看了文档,甚至查看了 C 源代码,但我不明白他们为什么将接受的基数限制为 2..36。有人知道吗?
问问题
1371 次
3 回答
7
正如其他人指出的那样,基数 < 2 渲染起来很麻烦。并且对于大于 ['0'..'9'] + ['a'..'z'] 的基数使用哪些字符没有约定俗成的协议,这就是标准方法不支持超出这些限制的基数的原因.
如果您真的想要自定义基数表示,则需要定义用于数字的符号字母表。这是一个小模块,它将为您提供该功能。
module CustomRadix
# generate string representation of integer, using digits from custom alphabet
# [val] a value which can be cast to integer
# [digits] a string or array of strings representing the custom digits
def self.custom_radix val, digits
digits = digits.to_a unless digits.respond_to? :[]
radix = digits.length
raise ArgumentError, "radix must have at least two digits" if radix < 2
i = val.to_i
out = []
begin
rem = i % radix
i /= radix
out << digits[rem..rem]
end until i == 0
out.reverse.join
end
# can be used as mixin, eg class Integer; include CustomRadix; end
# 32.custom_radix('abcd') => "caa" (200 base 4) equiv to 32.to_s(4).tr('0123','abcd')
def custom_radix digits
CustomRadix.custom_radix self, digits
end
end
示例使用:
$ irb
>> require '~/custom_radix'
=> true
>> CustomRadix.custom_radix(12345,'0'..'9')
=> "12345"
>> CustomRadix.custom_radix(12345,'.-')
=> "--......---..-"
>> funny_hex_digits = ('0'..'9').to_a + ('u'..'z').to_a
=> ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "u", "v", "w", "x", "y", "z"]
>> CustomRadix.custom_radix(255, funny_hex_digits)
=> "zz"
>> class Integer; include CustomRadix; end
=> Integer
>> (2**63).custom_radix(funny_hex_digits)
=> "8000000000000000"
>> (2**64+2**63+2**62).custom_radix(funny_hex_digits)
=> "1w000000000000000"
>> base64_digits = ('A'..'Z').to_a + ('a'..'z').to_a + ('0'..'9').to_a << '+' << '/'
=> ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "+", "/"]
>> 123456.custom_radix(base64_digits)
=> "eJA"
于 2012-03-22T21:19:38.083 回答
2
我对红宝石一无所知,但我知道有 10 个十进制数字加上 26 个字母数字。那是36。
于 2012-03-22T17:36:25.700 回答
1
您将如何呈现以 1 为底的数字?你将如何呈现以 37 为底的数字?基数300?
通常使用 0..9 和 A..F 表示十六进制数。继续使用字母表来表示更高的碱基是很直观的,但这只会让你达到 36 个。由于高碱基的用途很少(如果有的话 - 我从未见过),因此没有任何约定。可能除了 64 号基地,这是一种完全不同的野兽,特定于单一基地,而且也不是很老。此外,还有无数不兼容的变体,这只会加强我的观点。
至于基数 1:存在一元计数,但它并不是非常有用,在计算中更不常见,而且很容易模拟(只需连接n
相同字符的时间)。此外,人们可能对这个角色应该是什么有着截然不同的看法。
于 2012-03-22T17:44:24.617 回答