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("");
}
Answer from Quark on Stack Overflow
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();
}
🌐
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.
🌐
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 ...
🌐
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.
🌐
Blogger
duongame.blogspot.com › 2016 › 01 › javascript-hex-string-to-byte-array.html
Bentley: Javascript hex string to byte array
January 26, 2016 - // Convert a hex string to a byte array function hexToBytes(hex) { for (var bytes = [], 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) { for (var hex = [], i = 0; i < bytes.length; ...
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();
}
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.
🌐
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.
🌐
YouTube
youtube.com › alltech
hexadecimal to bytes in javascript - YouTube
Script that translates hexadecimal to a byte array in JavaScript Download source code at: https://drive.google.com/file/d/0B61-MHkMYqM4b0cwNVBrUlhZYkk/ Other...
Published: March 20, 2016
Views: 1K
🌐
xjavascript
xjavascript.com › blog › how-to-convert-hex-string-into-a-bytes-array-and-a-bytes-array-in-the-hex-string
How to Convert Hex String to Bytes Array and Bytes Array to Hex String Without Data Modification: Fixing Calculation Errors in JavaScript — xjavascript.com
The hex string "48656C6C6F" translates to the byte array [72, 101, 108, 108, 111], which is the ASCII encoding of "Hello". ... Even length: Valid hex strings must have an even number of characters (each byte = 2 hex chars).
🌐
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 - For example, the byte array ... We may need to convert a hex string to a byte array for various reasons. One reason is to decode data that was encoded using hex encoding. Hex encoding is a way of representing binary data as text using hexadecimal notation. It is often used to make binary data more readable or compatible with different systems or protocols.
🌐
GitHub
gist.github.com › don › 871170d88cf6b9007f7663fdbc23fe09
Convert hex string to ArrayBuffer · GitHub
Convert hex string to ArrayBuffer · Raw · hexStringToArrayBuffer.js · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
🌐
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