You can create a function converting a hex number to binary with something like this :

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

For formatting you just fill a string with 8 0, and you concatenate your number. Then, for converting, what you do is basicaly getting a string or number, use the parseInt function with the input number value and its base (base 16 for hex here), then you print it to base 2 with the toString function. And finally, you extract the last 8 characters to get your formatted string.


2018 Edit :

As this answer is still being read, I wanted to provide another syntax for the function's body, using the ES8 (ECMAScript 2017) String.padStart() method :

function hex2bin(hex){
    return (parseInt(hex, 16).toString(2)).padStart(8, '0');
}

Using padStart will fill the string until its lengths matches the first parameter, and the second parameter is the filler character (blank space by default).

End of edit


To use this on a full string like yours, use a simple forEach :

var result = ""
"21 23 00 6A D0 0F 69 4C E1 20".split(" ").forEach(str => {
  result += hex2bin(str)
})
console.log(result)

The output will be :

00100001001000110000000001101010110100000000111101101001010011001110000100100000

Answer from Seblor on Stack Overflow
Top answer
1 of 11
57

You can create a function converting a hex number to binary with something like this :

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

For formatting you just fill a string with 8 0, and you concatenate your number. Then, for converting, what you do is basicaly getting a string or number, use the parseInt function with the input number value and its base (base 16 for hex here), then you print it to base 2 with the toString function. And finally, you extract the last 8 characters to get your formatted string.


2018 Edit :

As this answer is still being read, I wanted to provide another syntax for the function's body, using the ES8 (ECMAScript 2017) String.padStart() method :

function hex2bin(hex){
    return (parseInt(hex, 16).toString(2)).padStart(8, '0');
}

Using padStart will fill the string until its lengths matches the first parameter, and the second parameter is the filler character (blank space by default).

End of edit


To use this on a full string like yours, use a simple forEach :

var result = ""
"21 23 00 6A D0 0F 69 4C E1 20".split(" ").forEach(str => {
  result += hex2bin(str)
})
console.log(result)

The output will be :

00100001001000110000000001101010110100000000111101101001010011001110000100100000

2 of 11
18

Unfortunately, previous answers seem not to be working with very large values (e.g., 512 bits so common in cryptography). This solution may be a bit slower, but it guarantees dealing with input of any length.

function hex2bin(hex){
    hex = hex.replace("0x", "").toLowerCase();
    var out = "";
    for(var c of hex) {
        switch(c) {
            case '0': out += "0000"; break;
            case '1': out += "0001"; break;
            case '2': out += "0010"; break;
            case '3': out += "0011"; break;
            case '4': out += "0100"; break;
            case '5': out += "0101"; break;
            case '6': out += "0110"; break;
            case '7': out += "0111"; break;
            case '8': out += "1000"; break;
            case '9': out += "1001"; break;
            case 'a': out += "1010"; break;
            case 'b': out += "1011"; break;
            case 'c': out += "1100"; break;
            case 'd': out += "1101"; break;
            case 'e': out += "1110"; break;
            case 'f': out += "1111"; break;
            default: return "";
        }
    }

    return out;
}
๐ŸŒ
W3Resource
w3resource.com โ€บ javascript-exercises โ€บ javascript-math-exercise-74.php
JavaScript - Hexadecimal number to binary equivalent
July 11, 2025 - Write a JavaScript function that converts a hexadecimal number to binary by mapping each hex digit to its 4-bit binary equivalent.
๐ŸŒ
GitHub
gist.github.com โ€บ faisalman โ€บ 4213592
Convert From/To Binary/Decimal/Hexadecimal in JavaScript ยท GitHub
and i am trying to convert it to binary but but getting 1000111 ... @jimmylogic you can decode your long hex data through this online tool : https://www.useotools.com/decode-hex
๐ŸŒ
YouTube
youtube.com โ€บ watch
How to Convert Hexadecimal to Binary in JavaScript Easy JS Tutorial for Beginners - YouTube
๐ŸŽฅ Hexadecimal to Binary Conversion in JavaScriptIn this quick JavaScript tutorial, you'll learn how to convert a hexadecimal number into its binary equivale...
Published: September 14, 2025
๐ŸŒ
Bytes
bytes.com โ€บ home โ€บ forum โ€บ topic โ€บ javascript โ€บ converting hex or binary to decimal and decimal to hex or binary javascript example
Converting Hex or Binary to Decimal and Decimal to Hex or Binary JavaScript Example - Post.Byes
July 4, 2009 - For example if you want to convert a decimal number into binary you just use base 2 instead of base 16: ... <html xmlns="http://www.w3.org/1999/xhtml"> <head></head> <body> <script type="text/javascript"> function ConvertToBinary(){ var numberValue = document.getElementById('NumberInput').value; var decNumber = Number(numberValue); var binaryNumber = decNumber.toString(2).toUpperCase(); document.getElementById('Result').value = binaryNumber; } function ConvertToDec(){ var binaryNumber = document.getElementById('NumberInput').value; var decNumber = parseInt(binaryNumber, 2); document.getElement
๐ŸŒ
npm
npmjs.com โ€บ package โ€บ hex-to-binary
hex-to-binary - npm
npm install hex-to-binary -S ยท var hexToBinary = require('hex-to-binary'); var hexString = 'AF30B'; // 10101111001100001011 console.log(hexToBinary(hexString)); hex ยท binary ยท transform ยท string ยท manipulation ยท npm i hex-to-binary ยท github.com/AVVS/hex-to-binary ยท
      ยป npm install hex-to-binary
    
Published: Mar 30, 2015
Version: 1.0.1
Author: Vitaly Aminev
๐ŸŒ
JSFiddle
jsfiddle.net โ€บ mowglisanu โ€บ 15h9o3d5
Hex data to binary file - JSFiddle - Code Playground
For now it's a BYOK implmentation which means you need to provide your own API Key โˆ’ you can get it for free.
Find elsewhere
๐ŸŒ
DEV Community
dev.to โ€บ dpc โ€บ daily-javascript-challenge-js-74-convert-hexadecimal-to-binary-155n
Daily JavaScript Challenge #JS-74: Convert Hexadecimal to Binary - DEV Community
January 16, 2025 - Hey fellow developers! ๐Ÿ‘‹ Welcome to today's JavaScript coding challenge. Let's keep those programming skills sharp! ... Write a function that converts a given string representing a hexadecimal number into its binary representation.
Top answer
1 of 4
13

Try this jsfiddle.

The more interesting functions to you are here. Not necessarily the cleanest or most efficient ones, but yea:

// converts binary string to a hexadecimal string
// returns an object with key 'valid' to a boolean value, indicating
// if the string is a valid binary string.
// If 'valid' is true, the converted hex string can be obtained by
// the 'result' key of the returned object
function binaryToHex(s) {
    var i, k, part, accum, ret = '';
    for (i = s.length-1; i >= 3; i -= 4) {
        // extract out in substrings of 4 and convert to hex
        part = s.substr(i+1-4, 4);
        accum = 0;
        for (k = 0; k < 4; k += 1) {
            if (part[k] !== '0' && part[k] !== '1') {
                // invalid character
                return { valid: false };
            }
            // compute the length 4 substring
            accum = accum * 2 + parseInt(part[k], 10);
        }
        if (accum >= 10) {
            // 'A' to 'F'
            ret = String.fromCharCode(accum - 10 + 'A'.charCodeAt(0)) + ret;
        } else {
            // '0' to '9'
            ret = String(accum) + ret;
        }
    }
    // remaining characters, i = 0, 1, or 2
    if (i >= 0) {
        accum = 0;
        // convert from front
        for (k = 0; k <= i; k += 1) {
            if (s[k] !== '0' && s[k] !== '1') {
                return { valid: false };
            }
            accum = accum * 2 + parseInt(s[k], 10);
        }
        // 3 bits, value cannot exceed 2^3 - 1 = 7, just convert
        ret = String(accum) + ret;
    }
    return { valid: true, result: ret };
}

// converts hexadecimal string to a binary string
// returns an object with key 'valid' to a boolean value, indicating
// if the string is a valid hexadecimal string.
// If 'valid' is true, the converted binary string can be obtained by
// the 'result' key of the returned object
function hexToBinary(s) {
    var i, k, part, ret = '';
    // lookup table for easier conversion. '0' characters are padded for '1' to '7'
    var lookupTable = {
        '0': '0000', '1': '0001', '2': '0010', '3': '0011', '4': '0100',
        '5': '0101', '6': '0110', '7': '0111', '8': '1000', '9': '1001',
        'a': '1010', 'b': '1011', 'c': '1100', 'd': '1101',
        'e': '1110', 'f': '1111',
        'A': '1010', 'B': '1011', 'C': '1100', 'D': '1101',
        'E': '1110', 'F': '1111'
    };
    for (i = 0; i < s.length; i += 1) {
        if (lookupTable.hasOwnProperty(s[i])) {
            ret += lookupTable[s[i]];
        } else {
            return { valid: false };
        }
    }
    return { valid: true, result: ret };
}
2 of 4
7

Why not using Array.prototype.reduce?

var binstr = "00001000010001000101010100001110"

function bin2hex(b) {
    return b.match(/.{4}/g).reduce(function(acc, i) {
        return acc + parseInt(i, 2).toString(16);
    }, '')
}

function hex2bin(h) {
    return h.split('').reduce(function(acc, i) {
        return acc + ('000' + parseInt(i, 16).toString(2)).substr(-4, 4);
    }, '')
}

console.log(binstr);
> 00001000010001000101010100001110
console.log(bin2hex(binstr));
> 0844550e
console.log(hex2bin(bin2hex(binstr)));
> 00001000010001000101010100001110

Link to jsfiddle here.

Notes:

  1. In bin2hex, if you want to convert also trailing chunks of less than 4 bits to hex, replace {4} with {1,4}. However, converting back the result to binary, will produce a string that differs from the original. For example, converting forth and back "111101" would produce "11110001".
  2. In hex2bin, binary values are left-padded with zeroes so as to have 4 binary digits for every hex digit.
๐ŸŒ
Bucarotechelp
bucarotechelp.com โ€บ design โ€บ jseasy โ€บ 82082701.asp
JavaScript Code for Binary to Hexadecimal - Hexadecimal to Binary Conversion
You don't really need JavaScript to convert a binary number to a hexadecimal number, however if you want to create a web application the JavaScript code to convert a binary number to hexadecimal number and to convert a hexadecimal number to a binary number is shown below.
๐ŸŒ
Danvk
danvk.org โ€บ hex2dec.html
Arbitrary precision Hex <-> Dec converter in JavaScript
We can implement a general add(x, y) function for these arrays of digits. This turns out to be all we need to do the base conversion. Since 2x = x + x, an add function lets you compute all the powers of two: ... Now, given a hex string, we can easily break it down into binary digits.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ utilities โ€บ design-hex-to-binary-converter
Online Design Hex to Binary Converter (Free & Easy to Use) - GeeksforGeeks
May 3, 2024 - JavaScript ยท Data Science ยท Machine ... Like Article ยท Like ยท Report ยท A Hex to Binary converter is a valuable tool that translates hexadecimal numbers (base-16) into binary numbers (base-2)....
๐ŸŒ
LinkedIn
linkedin.com โ€บ pulse โ€บ javascript-hexadecimal-binary-octal-representation-pranav-r-nayak-n-aso2c
JavaScript hexadecimal, binary, Octal representation.
December 11, 2023 - Binary literals - In Javascript ... Hexadecimal Literals - In JavaScript we can use hexadecimal literals using 0x (or X) followed by 0 to 9 or A to F....
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ binary-to-hexadecimal-converter-using-javascript
Binary to Hexadecimal Converter using JavaScript | GeeksforGeeks
August 2, 2024 - Facilitates Data Communication: Hexadecimal facilitates data exchange between systems, as it provides a concise and universally understood representation of binary information, aiding in interoperability. ... A binary number is a number expressed in the binary numeral system, which uses only two symbols 0 and 1. Decimal numbers are base 10 in a JavaScript number system that uses 10 digits from 0 to ...
๐ŸŒ
W3Resource
w3resource.com โ€บ javascript-exercises โ€บ javascript-math-exercise-3.php
JavaScript Math: Convert a decimal number to binary, hexadecimal or octal number - w3resource
July 11, 2025 - The code defines a function called "dec_to_bho()" which takes two parameters: a decimal number 'n' and a base ('B' for binary, 'H' for hexadecimal, or 'O' for octal).
๐ŸŒ
W3Schools
w3schools.com โ€บ js โ€บ tryit.asp
JavaScript Numbers
โฏRun Code Ctrl+Alt+R Save Code Ctrl+Alt+A Change Orientation Ctrl+Alt+O Change Theme Ctrl+Alt+D Go to Spaces Ctrl+Alt+P