ドキュメントを見て、Cソースを覗いても、受け入れられる基数が2..36に制限されている理由がわかりません。誰か知ってる?
3 に答える
他の人が指摘しているように、基数 < 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"
ruby については何も知りませんが、10 進数 10 桁と 26 桁の英字があることは知っています。それは36です。
基数 1 の数値をどのようにレンダリングしますか? 基数 37 で数値をどのようにレンダリングしますか? ベース300で?
16 進数には 0..9 と A..F を使用するのが一般的です。より高い基数にアルファベットを使用し続けることは直感的ですが、それでは 36 しか得られません。おそらくbase 64を除いて、これはまったく異なる獣であり、単一の塩基に固有であり、それほど古いものでもありません. また、無数の互換性のないバリアントがあり、私の主張を補強するだけです.
ベース 1 について: 単項カウントは存在しますが、それほど有用ではなく、コンピューティングではさらに一般的ではなく、エミュレートするのは非常に簡単です (n
同じ文字を連結するだけです)。その上、人々はおそらくそのキャラクターがどうあるべきかについて非常に異なる意見を持っています.