Non-decimal radices/Convert: Difference between revisions

m
→‎{{header|Ruby}}: did not provide method to convert from dec to base
m (→‎{{header|Ruby}}: newline before trans)
m (→‎{{header|Ruby}}: did not provide method to convert from dec to base)
Line 785:
 
{{trans|Tcl}}
<lang ruby>defmodule scanbase(str, base)BaseConvert
digitsDIGITS = %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}
res = 0
 
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)
str.to_s.downcase.each_char do |c|
dec2base(base2dec(str, basefrom), baseto)
idx = digits[0,base].find_index(c)
end
idx.nil? and raise ArgumentError, "invalid base-#{base} digit: #{c}"
 
res = res * base + idx
def base2dec(str, base)
raise ArgumentError, "base is invalid" unless base.between?(2, DIGITS.length)
res = 0
str.to_s.downcase.each_char do |c|
idx = digitsDIGITS[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
raise ArgumentError, "base is invalid" unless base.between?(2, DIGITS.length)
res = []
while n > 0
n, r = n.divmod(base)
res.unshift(DIGITS[r])
end
res.join("")
end
res
end
 
include BaseConvert
scanbase 255, 19 # => 822
p baseconvert("107h", 23, 7) # => "50664"
scanbase 39, 8 # => ArgumentError: invalid base-8 digit: 9</lang>
</lang>
 
=={{header|Slate}}==
Anonymous user