Non-decimal radices/Convert: Difference between revisions

Content added Content deleted
(Added Erlang)
Line 1,630:
 
=={{header|Ruby}}==
<lang ruby>s = 26.to_s(16) # returns the string 1a
i = '1a'.to_i(16) # returns the integer 26</lang>
Caution: <tt>to_i</tt> simply stops when it reaches an invalid character; it does not raise any exceptions. So sometimes it may appear to parse something and get a result, but it is only based on part of the input string:
Line 1,639:
{{trans|Tcl}}
<lang ruby>module BaseConvert
DIGITS = [*"0".."9", *"a".."z"]
DIGITS = %w{0 1 2 3 4 5 6 7 8 9 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}
 
def baseconvert(str, basefrom, baseto)
dec2base(base2dec(str, basefrom), baseto)
end
 
def base2dec(str, base)
raise ArgumentError, "base is invalid" unless base.between?(2, DIGITS.length)
str.to_s.downcase.each_char.inject(0) do |res, c|
res = 0
idx = DIGITS[0,base].find_indexindex(c)
str.to_s.downcase.each_char do |c|
idx = DIGITS[0,base].find_index(c)
idx.nil? and raise ArgumentError, "invalid base-#{base} digit: #{c}"
res = res * base + idx
end
res
end
 
def dec2base(n, base)
return "0" if n == 0
Line 1,664 ⟶ 1,662:
res.unshift(DIGITS[r])
end
res.join("")
end
end
 
include BaseConvert
p dec2base(26, 16) # => "1a"
p base2dec("1a", 16) # => 26
p baseconvert("107h", 23, 7) # => "50664"</lang>