You can use Buffer.from(str, [encoding]) to perform the conversion.

Buffer.from(str, 'hex');
Answer from Jake Holzinger on Stack Overflow
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Uint8Array › fromHex
Uint8Array.fromHex() - JavaScript - MDN Web Docs
July 10, 2025 - The Uint8Array.fromHex() static method creates a new Uint8Array object from a hexadecimal string. This method parses the string into a byte array.
🌐
npm
npmjs.com › package › hex-to-array-buffer
hex-to-array-buffer - npm
Turn a string of hexadecimal characters into an ArrayBuffer. npm install --save hex-to-array-buffer · import hexToArrayBuffer from 'hex-to-array-buffer' const buffer = hexToArrayBuffer('ceae96a325e1dc5dd4f405d905049ceb') console.log(buffer) ...
      » npm install hex-to-array-buffer
    
Top answer
1 of 7
86

Convert a hex string to a byte array and vice versa

note: implementation from crypto-js, though now out of date and slightly altered

// Convert a hex string to a byte array
function hexToBytes(hex) {
    let bytes = [];
    for (let c = 0; c < hex.length; c += 2)
        bytes.push(parseInt(hex.substr(c, 2), 16));
    return bytes;
}

// Convert a byte array to a hex string
function bytesToHex(bytes) {
    let hex = [];
    for (let i = 0; i < bytes.length; i++) {
        let current = bytes[i] < 0 ? bytes[i] + 256 : bytes[i];
        hex.push((current >>> 4).toString(16));
        hex.push((current & 0xF).toString(16));
    }
    return hex.join("");
}
2 of 7
14

Update: Scroll down for solution... Live Demo

The issue: you are using a lossy conversion to hex, which cannot be reversed.

var p = parseHexString(createHexString(rsa_privk[0]));

This will never be same as rsa_privk[0].

Because, createHexString() only uses the last 2 bytes from each array element.

Example:

rsa_privk[0] : [123676133, 198914513, 129998601, 245147334, 11918451, 206998232, 96766191, 75984899, 177840095, 106709334, 10180427, 208237547, 119814814, 127003446, 189062377, 84099480, 220452154, 250519075, 267883908, 115471915, 165124106, 238628722, 169382478, 42320122, 95982405, 80725759, 89608310, 85166267, 200925925, 254033325, 86971506, 191278317, 127411298, 180195794, 142776693, 188738169, 39016]

createHexString(rsa_privk[0]) : e5d109c673d8ef03df564beb9e36e9983a23842b0a724efa45ff76bbe5ad72ed62d2757968

parseHexString(createHexString(rsa_privk[0])) : [229, 209, 9, 198, 115, 216, 239, 3, 223, 86, 75, 235, 158, 54, 233, 152, 58, 35, 132, 43, 10, 114, 78, 250, 69, 255, 118, 187, 229, 173, 114, 237, 98, 210, 117, 121, 104] 

Update : Working Solution...

The two functions... the hex always contains 8 byte blocks, each for each element in the array...

function parseHexString(str) { 
    var result = [];
    while (str.length >= 8) { 
        result.push(parseInt(str.substring(0, 8), 16));

        str = str.substring(8, str.length);
    }

    return result;
}

function createHexString(arr) {
    var result = "";
    var z;

    for (var i = 0; i < arr.length; i++) {
        var str = arr[i].toString(16);

        z = 8 - str.length + 1;
        str = Array(z).join("0") + str;

        result += str;
    }

    return result;
}

Test code...

function test() {   
    a = [123676133, 198914513, 129998601, 245147334, 11918451, 206998232, 96766191, 75984899, 177840095, 106709334, 10180427, 208237547, 119814814, 127003446, 189062377, 84099480, 220452154, 250519075, 267883908, 115471915, 165124106, 238628722, 169382478, 42320122, 95982405, 80725759, 89608310, 85166267, 200925925, 254033325, 86971506, 191278317, 127411298, 180195794, 142776693, 188738169, 39016];

    console.log("Input");
    console.log(a);

    b = createHexString(a);

    console.log("Hex");
    console.log(b);

    c = parseHexString(b); 

    console.log("Output");
    console.log(c);

    if(checkIfEqual(a, c)) {
        alert("Same");
    }
}

function checkIfEqual(arr1, arr2) {
    if (arr1.length != arr2.length) {
        return false;
    }
    //sort them first, then join them and just compare the strings
    return arr1.sort().join() == arr2.sort().join();
}
🌐
Programming Idioms
programming-idioms.org › idiom › 176 › hex-string-to-byte-array › 2567 › js
Hex string to byte array, in JS
int i, n = s.length(); byte a[] = new byte[n / 2]; for (i = 0; i < n; i = i + 2) a[i / 2] = (byte) fromHexDigits(s, i, i + 2); ... Do you know the best way to do this in your language ? New implementation... ... s .split('') .map((el, ix, arr) => ix % 2 ? null : el + arr[ix + 1]) .filter(el ...
🌐
npm
npmjs.com › package › convert-hex
convert-hex - npm
November 21, 2013 - JavaScript component to convert to/from hex strings and byte arrays.
      » npm install convert-hex
    
Published: Nov 21, 2013
Version: 0.1.0
Find elsewhere
🌐
GitHub
gist.github.com › llzes › 7e0a324239653f32f8eb78a09208de52
Byte to Hex and Hex to Byte in JavaScript. · GitHub
Byte to Hex and Hex to Byte in JavaScript. GitHub Gist: instantly share code, notes, and snippets.
🌐
Stack Overflow
stackoverflow.com › questions › 51595321 › convert-byte-array-to-hex-string-using-mongoose-node-js › 51596350
node.js - Convert byte array to Hex string using Mongoose Node JS - Stack Overflow
In java to convert hex string to byte array we have: byte[] bytes = DatatypeConverter.parseHexBinary(s); ... I want to similar function which does the same job in node js.
🌐
Prussiafan
prussiafan.club › posts › hex-to-bytes-and-back
Hex to Bytes and Back - prussiafan.club
September 15, 2023 - [3]: In case you were wondering, I do write the hex_chars array out every time... slightly painful, but it's too much work to copy paste it from somewhere · [4]: Note that the Math.floor means that this function only works with an even hex string length, since an odd hex string length would mean there's half of a byte (aka a nybble) being used, which is rare-ish.
Top answer
1 of 1
5

Further, you cannot simply push a value of type Integer to a byte array. Integers are represented with 32 bit (4 bytes), so you first have to "split" such number while computing the single bytes one by one:

intToByteArray = function(intToConvert) {
    var byteArray = new Array(4)

    for(var i = 0; i < byteArray.length; i++) {
        var byte = intToConvert & 0xff;
        byteArray[i] = byte;
        intToConvert = (intToConvert - byte) / 256 ;
    }

    return byteArray;
};     

Demonstration of back and forth conversion (JS-Fiddle)


Explanation of code lines

  1. At first, we declare an array of bytes:

    var byteArray = new Array(4)
    

    Array: [00000000, 00000000, 00000000, 00000000]

  2. By using the bit-wise AND operator &, we "capture" the first 8 bits while assigning the resulting value to a new variable:

    var byte = intToConvert & 0xff;
    

    What's happening with our variables:

    intToConvert: 10101010 10101010 10101010 10101010
    AND "0xff": 11111111 -------- -------- --------
    Results in: 10101010
  3. Then, we put the resulting single byte to the actual index of the temporary byte array:

    byteArray[i] = byte;
    

    Array: [10101010, 00000000, 00000000, 00000000]

  4. Now, we only have to subtract the value just added to the array and remove one byte from the integer variable:

    intToConvert = (intToConvert - byte) / 256 ;
    

    2863311530 - 170 = 2863311360
    2863311360 / 256 = 11184810

    2863311360 => 10101010 10101010 10101010 00000000
      11184810 =>          10101010 10101010 10101010
    

Continuing with this loop will transfer byte by byte from the Integer to the temporary byte array. So we will get a byte array of 4 single bytes representing one integer or two Character of the hexadecimal String.


How to convert byte to Integer is well explained here.
So your updated hex2bin(String) should look like:

function hex2bin(hexString) {
    var bytes = new Array(hexString.length / 2);

    for(var i = 0; i < hexString.length-1; i+=2) {
        bytes.push(
            intToByteArray(
                parseInt(hexString.substr(i, 2), 16)
            )
        );
    }

    StringBuilder sb = new StringBuilder(bytes.length * 8);
    for(byte b : bytes) {
        sb.append(Integer.toBinaryString((b & 0xFF) + 0x100).substring(1));    
    }
    return sb.toString();
}
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Uint8Array › setFromHex
Uint8Array.prototype.setFromHex() - JavaScript | MDN
The setFromHex() method of Uint8Array instances populates this Uint8Array object with bytes from a hex-encoded string, returning an object indicating how many bytes were read and written. This method parses the string into a byte array.
🌐
Stack Overflow
stackoverflow.com › questions › 71737750 › is-there-any-equivalent-function-in-javascript-of-bytes-fromhex
node.js - Is there any equivalent function in javascript of bytes.fromhex() - Stack Overflow
I want to convert my hexadecimal string to byte literal in javascript bytes.fromhex(get_hex_coded_ascii(payload_size + payload + str(crc)) this code is in python but I want to change this into java...
🌐
Yarn
yarnpkg.com › package
Yarn
Yarn is a package manager that doubles down as project manager. Whether you work on simple projects or industry monorepos, whether you're an open source developer or an enterprise user, Yarn has your back · First package manager built specifically around workspaces, Yarn lets you split your ...
🌐
GitHub
gist.github.com › amorri40 › 3430429
Javascript Byte to hex · GitHub
May 20, 2019 - Clone this repository at &lt;script src=&quot;https://gist.github.com/amorri40/3430429.js&quot;&gt;&lt;/script&gt; Save amorri40/3430429 to your computer and use it in GitHub Desktop. Download ZIP · Javascript Byte to hex · Raw · byteToHex.js · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below.