0

I watched a few videos on this, cannot seem to convert to Hex or Binary.

I want to take the input, and log the hex and the binary of the input

var hexLetters = "0123456789ABCDEF".split("");

var decimalNum = Number(window.prompt("Enter a decimal number to convert"));

var binaryNum= "";

    console.log("The number " + decimalNum + " in binary is: ") 
    console.log(Number.parseInt(binaryNum, 2)); // returns an integer of the specified radix or base.

var hexNum = "";


    console.log("The number " + decimalNum + " in hexadecimal is: ")
    console.log(Number.parseInt(hexNum, 16));
Dominik
  • 6,078
  • 8
  • 37
  • 61
Fredom304
  • 15
  • 2
  • 2
    you're passing `binaryNum` and `hexNum` to `parseInt`, which is an empty string so won't work properly. You just need to pass `decimalNum` instead and this should work – Robin Zigmond Mar 02 '21 at 20:34
  • 1
    Does this answer your question? [How to convert decimal to hexadecimal in JavaScript](https://stackoverflow.com/questions/57803/how-to-convert-decimal-to-hexadecimal-in-javascript) – derpirscher Mar 02 '21 at 20:35
  • PS since you're using `parseInt` anyway, you don't need to convert the user's input to a number with `Number`. `parseInt` should only ever be passed a string. (Although it does technically work if you pass a number - it gets coerced to a string first - I don't recommend it.) – Robin Zigmond Mar 02 '21 at 20:35

1 Answers1

0

I would use toString(base) instead of Number.parseInt():

var hexLetters = "0123456789ABCDEF".split("");


var decimalNum = Number(window.prompt("Enter a decimal number to convert"));


var binaryNum= "";

console.log("The number " + decimalNum + " in binary is: ");
console.log(decimalNum.toString(2)); // returns an integer of the specified radix or base.

var hexNum = "";


console.log("The number " + decimalNum + " in hexadecimal is: ");
console.log(decimalNum.toString(16));
Raz K
  • 167
  • 8