Advertisement
Guest User

Untitled

a guest
Jun 19th, 2019
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.89 KB | None | 0 0
  1. # Write a hexadecimal_to_integer method that converts a string
  2. # representing a hexadecimal number to its integer value.
  3. # You may not use any of the standard conversion methods available in Ruby,
  4. # such as String#to_i, Integer(), etc
  5.  
  6. def map_char
  7. map = {}
  8. increment = 10
  9. (0..9).map do |num|
  10. map["#{num}"] = num
  11. end
  12. ('a'..'f').map do |alpha|
  13. map["#{alpha}"] = increment
  14. increment += 1
  15. end
  16. map
  17. end
  18.  
  19. def convert_string_integer!(key)
  20. map_char[key]
  21. end
  22.  
  23. def decimal_by_base16(decimal, index)
  24. decimal * (16**index)
  25. end
  26.  
  27. def list_of_base16(string)
  28. index = string.size - 1
  29. decimals = []
  30. string.downcase.each_char do |char|
  31. int = convert_string_integer!(char)
  32. decimals << decimal_by_base16(int, index)
  33. index -= 1
  34. end
  35. decimals
  36. end
  37.  
  38. def hexadecimal_to_integer(string)
  39. list_of_base16(string).inject { |base, num| base + num }
  40. end
  41.  
  42. p hexadecimal_to_integer('4D9f')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement