Convert binary to hexadecimal in JavaScript & ReactJs – Code Example

Total
0
Shares

In this article we will provide you the code to convert a binary number to hexadecimal in Javascript & ReactJs. The process is to first convert the binary number to decimal number and then from decimal to hexadecimal. Check out the code –

function binaryToDecimal(x) {
  const parsed = parseInt(x, 2);
  if (isNaN(parsed)) { return 0; }
  return parsed;
}

function decimalToHex(x) {
  var parsed = x;
  
  hexstr = ""
  while(parsed > 0) {
    var value = parsed % 16
    hexstr = (
      value == 10 ? "A" : (
        value == 11 ? "B" : (
        value == 12 ? "C" : (
        value == 13 ? "D" : (
        value == 14 ? "E" : (
        value == 15 ? "F": value)))))) + hexstr
    parsed = parseInt(parsed / 16)
  }
  
  return '0x'+ hexstr;
}

function binaryToHex(x) {
  return decimalToHex(binaryToDecimal(s))
}

console.log(binaryToHex('1001'));