Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #===============================================================================
- # Methods for conversion to binary
- # conversion_timer : gets the time taken to perform conversion. Also acts as
- # a block handler for the conversion.
- # decimal_binary(n) : converts a decimal number to a binary number, n being
- # the number for conversion.
- # binary_decimal(n) : converts a binary number to a decimal number, n being
- # the number for conversion.
- # unary_decimal(n) : converts a unary number to a decimal number, n being
- # the number for conversion.
- # decimal_unary(n) : converts a decimal number to a unary number, n being
- # the number for conversion.
- #===============================================================================
- def conversion_timer(&proc)
- started = Time.now
- yield if block_given?
- stopped = Time.now
- res = stopped - started
- res
- end
- def decimal_binary(n)
- conversion_timer {
- res = []
- while n != 0
- new_n = n >> 1
- res << ((n == new_n << 1) ? '0' : '1')
- n = new_n
- end
- n = res.reverse.join.to_i
- }
- n
- end
- def binary_decimal(n)
- conversion_timer {
- res = 0
- exp = 1
- missing = 0
- n.to_s.reverse.each_byte { |s|
- if s == 49
- exp <<= missing
- res += exp
- missing = 1
- else
- missing += 1
- end
- }
- n = res
- }
- n
- end
- def unary_decimal(n)
- n.to_s.size
- end
- def decimal_unary(n)
- s = ''
- n.times do s += '1' end
- s
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement