class Bin2dec

Public Class Methods

convert(num) click to toggle source

Let n be the number of digits in the number. For example, 104 has 3 digits, so n=3. Let b be the base of the number. For example, 104 is decimal so b = 10. Let s be a running total, initially 0. For each digit in the number, working left to right do:

Subtract 1 from n. 
Multiply the digit times b^n and add it to s.

When your done with all the digits in the number, its decimal value will be s

# File lib/bin2dec.rb, line 13
def self.convert(num)
  n = num.length
  s = 0
  
  n.times do | i |
    temp = num[i].to_i

    if !numeric?(num[i])
      raise "Error: input contains illegal characters"
    end

    if ((temp == 0) || (temp == 1))
      n-= 1       
      s+= temp * (2**n)
    else
      raise "Error: not a binary number"        
    end
  end

  return s
end
numeric?(input) click to toggle source
# File lib/bin2dec.rb, line 35
def self.numeric?(input)
  input =~ /[0-9]/
end