Method: BCD.decode

Defined in:
lib/bcd.rb

.decode(bcd) ⇒ Object

Translates binary coded decimal into an integer

Raises:

  • (ArgumentError)


9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/bcd.rb', line 9

def self.decode(bcd)
  raise ArgumentError, 'Argument is not numeric' unless bcd.is_a? Numeric
  raise ArgumentError, 'Cannot be a negative integer' if bcd < 0

  binstring = ''
  while true do
    q, r = bcd.divmod(10)
    nibble = r.to_s(2)
    while nibble.length < 4 do
      nibble.prepend('0')
    end
    binstring.prepend(nibble)
    q == 0 ? break : bcd = q
  end

  binstring.to_i(2)
end