Class: Bin2dec

Inherits:
Object
  • Object
show all
Defined in:
lib/bin2dec.rb

Class Method Summary collapse

Class Method Details

.convert(num) ⇒ Object

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



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# 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) ⇒ Boolean

Returns:

  • (Boolean)


35
36
37
# File 'lib/bin2dec.rb', line 35

def self.numeric?(input)
  input =~ /[0-9]/
end