Decimal To Hex Algorithm

The Decimal to Hexadecimal Algorithm is a widely used numerical conversion method that allows us to transform a decimal (base-10) number into its equivalent representation in the hexadecimal (base-16) numeral system. The hexadecimal system, composed of 16 unique symbols (0-9 and A-F), is particularly useful in computer science and programming due to its compatibility with binary code (base-2), enabling more efficient representation and interpretation of larger numbers. To perform the Decimal to Hexadecimal Algorithm, one must first divide the decimal number by 16 and record both the quotient (whole number result) and the remainder. The remainder represents the least significant digit (rightmost digit) in the hexadecimal number. Next, the process is repeated using the quotient as the new dividend, and the new remainder becomes the next least significant digit in the hexadecimal representation. This process is continued until the quotient becomes zero. The hexadecimal number is then constructed by arranging the remainders in reverse order, with the last remainder being the most significant digit (leftmost digit). If any remainder is greater than 9, it is represented by the corresponding letter (A = 10, B = 11, C = 12, D = 13, E = 14, F = 15).
function intToHex (num) {
  switch (num) {
    case 10: return 'A'
    case 11: return 'B'
    case 12: return 'C'
    case 13: return 'D'
    case 14: return 'E'
    case 15: return 'F'
  }
  return num
}

function decimalToHex (num) {
  const hexOut = []
  while (num > 15) {
    hexOut.push(intToHex(num % 16))
    num = Math.floor(num / 16)
  }
  return intToHex(num) + hexOut.join('')
}

// test cases
console.log(decimalToHex(999098) === 'F3EBA')
console.log(decimalToHex(123) === '7B')

LANGUAGE:

DARK MODE: