-2

What would the function be for when the user inputs, it converts the input to both hex and binary?

The algorithm for converting from decimal to binary is this:

  • Take your decimal number and determine the remainder if you divide that number by two. The remainder is now the bit in your ONES (2^0) place. Hint: the modulo operator % will give you the REMAINDER of a division. For example, 5%2 is 1 because the remainder of dividing 5 by 2 is 1. 4%2 is 0, because there is no remainder.

  • Now, we're going to update your decimal number: divide the decimal number and round down to get your NEW decimal number

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


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


var binaryNum= "";
*  binary conversion *


console.log("The number " + decimalNum + " in binary is: ")
console.log(binaryNum);


var hexNum = "";
*binary conversion*

/************************************* */

console.log("The number " + decimalNum + " in hexadecimal is: ")
console.log(hexNum);

What would the function be for when the user inputs, it converts the input to both hex and binary

Fredom304
  • 15
  • 2

2 Answers2

0

You can create a function to convert a hex number to binary:

function hexToBin(hex){
return ("00000000" + (parseInt(hex, 16)).toString(2)).substr(-8);

}

0

To play in safe the user must choose the target from (Hex, Binary, decimal) to (Hex, Binary, decimal) to know the right function to use

 // 1. Convert to Binary

    function convertToBinary(number) {
        let bin = 0;
        let rem, i = 1, step = 1;
        while (number != 0) {
            rem = number % 2;
            console.log(
                `Step ${step++}: ${number}/2, Remainder = ${rem}, Quotient = ${parseInt(number/2)}`
            );
            number = parseInt(number / 2);
            bin = bin + rem * i;
            i = i * 10;
        }
        console.log(`Binary: ${bin}`);
    }
    
    convertToBinary(2);

    
    // 2. Convert to Hex 

    function hex2bin(hex){
        return (parseInt(hex, 16).toString(2)).padStart(8, '0');
    }
    function convertHexToBinary(hex) {
      var result = "";
    hex.split(" ").forEach(sting => {
      result += hex2bin(sting)
    })
    console.log(result)
    }
    
    convertHexToBinary('2AB');

Hex answer credit for https://stackoverflow.com/a/45054052/14292804

Binary answer credit for https://www.programiz.com/javascript/examples/decimal-binary#:~:text=The%20parseInt()%20method%20is,decimal%20number%20to%20binary%20number.

Tawfeeq Amro
  • 605
  • 7
  • 15