Links

ΜΆ
Adam I. Gerard
ISU
NIU
CS MS TBD

Hexadecimal

Just your standard hexadecimal conversion.

  • Difficulty: Easy
  • Kind: Recursion
  • Platform: Basic Concepts
  • Solved: N/A
  • Time Complexity: O(N)
  • Space Complexity: O(N)
  • Answer Rank: Top N/A

Insights

Hexadecimals represent number values using base 16. To convert a number into hexadecimal form involves recursively dividing the number by 16 and calculating any remainder. The remainder is used to calculate the symbol at each step. These values are passed to the next recurse call. Use the 2-complement for negative decimals.
// 0-9
// A-F represent 10-15
var NUMS = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"];

function decimalToHexadecimal(num, remainders = []) {
  // Handle negative decimal numbers using complement
  if (num < 0) {
    num = num + Math.pow(2, 32)
  }

  var r = num % 16,d = Math.floor(num / 16);
  print_console(`Remainder: ${r}`);
  print_console(`Long Division: ${d}`);

  remainders.push(NUMS[r]);
  if (d < 1) return remainders.reverse().join("");
  return decimalToHexadecimal(d, remainders);
}

function hexToDecimal(hex) {
  var num = 0
  
  // Check if negative hexadecimal (will always start with 9-F)
  if (NUMS.indexOf(hex.charAt(0)) >= 8) {
    num -= Math.pow(2, 32)
  }
  
  var order = hex.length;

  for (var i = 0; i < hex.length; i++) {
    order--;
    var n = NUMS.indexOf(hex.charAt(i));
    num += n * Math.pow(16, order);
  }

  return num;
}

window.onload = function() {
  print_console(decimalToHexadecimal(100));
  print_console(decimalToHexadecimal(1000));
  print_console(decimalToHexadecimal(-111));
  print_console(hexToDecimal("64"));
  print_console(hexToDecimal("3E8"));
  print_console(hexToDecimal("FFFFFF91"));
};

Test Cases

      Links