Module: BCD
- Defined in:
- lib/bcd.rb
Overview
Methods to translate to and from binary coded decimal
- Author
-
David Crosby <[email protected]>
- Copyright
-
Copyright 2013-2022 David Crosby
- License
-
BSD 2-clause
Class Method Summary collapse
-
.decode(bcd) ⇒ Object
Translates binary coded decimal into an integer : (Integer) -> Integer.
-
.encode(int) ⇒ Object
Translate an integer into binary coded decimal : (Integer) -> Integer.
Class Method Details
.decode(bcd) ⇒ Object
Translates binary coded decimal into an integer : (Integer) -> Integer
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
# File 'lib/bcd.rb', line 14 def self.decode(bcd) raise ArgumentError, "Argument is not Integer" unless bcd.is_a? Integer raise ArgumentError, "Cannot be a negative integer" if bcd.negative? binstring = String.new loop do q, r = bcd.divmod(10) nibble = r.to_s(2) nibble.prepend("0") while nibble.length < 4 binstring.prepend(nibble) q.zero? ? break : bcd = q end binstring.to_i(2) end |
.encode(int) ⇒ Object
Translate an integer into binary coded decimal : (Integer) -> Integer
32 33 34 35 36 37 38 39 40 41 42 43 |
# File 'lib/bcd.rb', line 32 def self.encode(int) raise ArgumentError, "Argument is not Integer" unless int.is_a? Integer raise ArgumentError, "Cannot be a negative integer" if int.negative? bcdstring = String.new while int.positive? nibble = int % 16 bcdstring.prepend(nibble.to_s) int >>= 4 end bcdstring.to_i end |