Non-decimal radices/Convert: Difference between revisions

Content added Content deleted
(Added Erlang)
Line 1,630: Line 1,630:


=={{header|Ruby}}==
=={{header|Ruby}}==
<lang ruby>s = 26.to_s(16) # returns the string 1a
<lang ruby>s = 26.to_s(16) # returns the string 1a
i = '1a'.to_i(16) # returns the integer 26</lang>
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:
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: Line 1,639:
{{trans|Tcl}}
{{trans|Tcl}}
<lang ruby>module BaseConvert
<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)
def baseconvert(str, basefrom, baseto)
dec2base(base2dec(str, basefrom), baseto)
dec2base(base2dec(str, basefrom), baseto)
end
end

def base2dec(str, base)
def base2dec(str, base)
raise ArgumentError, "base is invalid" unless base.between?(2, DIGITS.length)
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].index(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}"
idx.nil? and raise ArgumentError, "invalid base-#{base} digit: #{c}"
res = res * base + idx
res = res * base + idx
end
end
res
end
end

def dec2base(n, base)
def dec2base(n, base)
return "0" if n == 0
return "0" if n == 0
Line 1,664: Line 1,662:
res.unshift(DIGITS[r])
res.unshift(DIGITS[r])
end
end
res.join("")
res.join
end
end
end
end


include BaseConvert
include BaseConvert
p dec2base(26, 16) # => "1a"
p base2dec("1a", 16) # => 26
p baseconvert("107h", 23, 7) # => "50664"</lang>
p baseconvert("107h", 23, 7) # => "50664"</lang>