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 };
}
Answer from yanhan on Stack Overflow
🌐
DEV Community
dev.to › bryanvieta › javascript-to-convert-binary-to-hex-13ke
Javascript to convert binary to hex - DEV Community
April 23, 2021 - The Bignumber.js library is not an inbuilt library in Javascript. You need to import the script in the head tag. Just copy and paste the following code in the tag. <script src="https://cdnjs.cloudflare.com/ajax/libs/bignumber.js/8.0.2/bignumber.min.js" integrity="sha512-7UzDjRNKHpQnkh1Wf1l6i/OPINS9P2DDzTwQNX79JxfbInCXGpgI1RPb3ZD+uTP3O5X7Ke4e0+cxt2TxV7n0qQ==" crossorigin="anonymous"></script> And done! You have built the binary to hex converter done.
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.
🌐
GitHub
gist.github.com › faisalman › 4213592
Convert From/To Binary/Decimal/Hexadecimal in JavaScript · GitHub
All of your examples convert it to a hex string. Copy link · Copy Markdown · Thanks a lot guy ! This code was very helpful for me ! Copy link · Copy Markdown · Is there a reason not to just do it like this? /*jshint browser:true, devel:true*/ /*jshint -W097*/ //DEVEL 'use strict'; /** * Convert From/To Binary/Decimal/Hexadecimal in JavaScript * https://gist.github.com/faisalman * * Copyright 2012-2015, Faisalman <fyzlman@gmail.com> * Licensed under The MIT License * http://www.opensource.org/licenses/mit-license */ var convertBase = function () { function convertBase(baseFrom, baseTo) { re
🌐
GeeksforGeeks
geeksforgeeks.org › binary-to-hexadecimal-converter-using-javascript
Binary to Hexadecimal Converter using JavaScript | GeeksforGeeks
August 2, 2024 - A string must follow the pattern so that it can be converted into a date. A string can be converted into a date in JavaScript through the following ways: Table of Content Using JavaScript Date() constructorUsing JavaScript toDat ... Given a number and the task is to convert the number from decimal to hex.
🌐
Webdevtutor
webdevtutor.net › blog › javascript-binary-string-to-hex
Converting Binary Strings to Hexadecimal in JavaScript
Convert to Hexadecimal: Once you have the integer value, you can convert it to a hexadecimal string using the toString(16) method. This method converts the number to a string representing the hexadecimal value. javascript // Binary string to convert const binaryString = '11010101';
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;
}
Find elsewhere
🌐
W3Resource
w3resource.com › javascript-exercises › javascript-math-exercise-74.php
JavaScript - Hexadecimal number to binary equivalent
July 11, 2025 - Unlike the decimal system representing numbers using 10 symbols, hexadecimal uses 16 distinct symbols, most often the symbols "0"–"9" to represent values 0 to 9, and "A"–"F" (or alternatively "a"–"f") to represent values from 10 to 15. A binary number is a number expressed in the base-2 numeral system or binary numeral system, a method of mathematical expression which uses only two symbols: typically "0" (zero) and "1" (one).
🌐
Sling Academy
slingacademy.com › article › javascript-convert-a-byte-array-to-a-hex-string-and-vice-versa
JavaScript: Convert a byte array to a hex string and vice versa - Sling Academy
March 13, 2023 - This concise and straightforward article shows you how to convert a byte array into a hex string (hexadecimal string) and vice versa in modern JavaScript (ES6 and above). ... A hex string is a string that represents binary data using hexadecimal notation.
🌐
Webdevtutor
webdevtutor.net › blog › javascript-bin2hex
Converting Binary to Hexadecimal in JavaScript: A Complete Guide
There are several ways to convert binary data to hexadecimal in JavaScript. One common approach is to use bitwise operators and string manipulation to perform the conversion.
🌐
Liangshunet
liangshunet.com › en › 202005 › 332182170.htm
Javascript convert string to hex number and hex to string(charCodeAt, toString and parseInt)-Lionsure
May 24, 2020 - Then use toString(16) to convert Unicode value to hexadecimal, and finally use slice(-4) to intercept four digits from right. function ConvertStringToHex(str) { var arr = []; for (var i = 0; i < str.length; i++) { arr[i] = ("00" + str.charCodeAt(i).toString(16)).slice(-4); } return "\\u" + ...
🌐
Webdevtutor
webdevtutor.net › blog › javascript-binary-to-hex
Converting Binary to Hexadecimal in JavaScript: A Step-by-Step Guide
In this example, we loop through the binary string and convert each bit to a hexadecimal digit using simple arithmetic operations. We then concatenate these digits to form the final hexadecimal string. ... Converting binary to hexadecimal in JavaScript is a useful skill for any programmer.
🌐
Functionfountain
functionfountain.com › en › javascript › convert-binary-to-hexadecimal
Learn to Convert Binary Numbers to Hexadecimal using JavaScript | Programming Learning Site| Function Fountain
March 14, 2026 - After converting the binary number to decimal, the next step is to convert the decimal to a hexadecimal. To convert a decimal into a hexadecimal number, divide the decimal number by 16 and keep the remainder.
🌐
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 - You pass this method the string containing the hex value as the first parameter and 16 as second parameter to indicate that the string is a base 16 number. This will return you a Number Object that is the decimal (base 10) equivalent to the hex value. ... <html xmlns="http://www.w3.org/1999/xhtml"> ...