ruby - 为什么 Ruby 中的 FixNum#to_s 方法只接受从 2 到 36 的基数?

标签 ruby radix

我查看了文档甚至浏览了 C 源代码,但我不明白为什么他们将可接受的基数限制为 2..36。有人知道吗?

最佳答案

正如其他人所指出的,radix < 2 渲染起来很麻烦。并且对于大于 ['0'..'9'] + ['a'..'z'] 的基数使用什么字符没有约定俗成的协议(protocol),这就是标准方法不支持超出这些限制的基数的原因.

如果您真的想要自定义基数表示,则需要定义用于数字的符号字母表。这是一个可以为您提供该功能的小模块。

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 - 为什么 Ruby 中的 FixNum#to_s 方法只接受从 2 到 36 的基数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9827498/

相关文章:

ruby-on-rails - 尝试访问连接表Rails中的属性

ruby - 无法通过 gsub 和 ||= ruby​​ 方法解析多个电话号码

python - 从字符串转换为 base-64 中的数字

java - 有没有办法保留或修改代码内基数信息?

ruby 数组检查 nil 数组

ruby-on-rails - 使用mongodb ruby​​驱动连接rails API应用程序和mongodb时要修改哪个文件

java - 试图从 Java 解密 attr_encrypted 存储值

inheritance - 继承类是否应该在基类的同一个cs文件中?

c++ - 有什么办法可以用 base64 计算出来吗?

c# - 从继承类获取特定方法