Search⌘ K
AI Features

Solution: Number Base Conversion

Explore how to convert numbers between decimal and hexadecimal bases using various Ruby techniques. Learn manual conversion methods with arrays and hashes as well as built-in methods like to_s and to_i with base arguments to perform conversions effectively.

Decimal to hex

Ruby 3.1.2
hex_digit = "0123456789abcdef".split("")
hexadecimal = ""
while(number != 0)
hexadecimal = hex_digit[number % 16].to_s + hexadecimal
number = number / 16
end
Did you find this helpful?

Explanation

  • Line 1: We create an array of characters representing hex values against the decimal numbers 0–15.

  • Line 4: The remainder—from the division of number by 16—is first converted to a hexadecimal string and prepended to the string hexadecimal.

  • Line 5: number is updated so that it stores the quotient from ...