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
🌐
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.
🌐
GitHub
gist.github.com › myfreeer › 055d00ea02395482aa1405bd82d246e7
Convert bytes to string Javascript · GitHub
Convert bytes to string Javascript · Raw · hex2string.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.
Discussions

javascript - How to convert hex string into a bytes array, and a bytes array in the hex string? - Stack Overflow
The following code procedure bytes = parseHexString (createHexString (bytes)) leads to updated of bytes, what I would like to avoid. And as a result calculations are not correct. More on stackoverflow.com
🌐 stackoverflow.com
Byte array to Hex string conversion in javascript - Stack Overflow
You need to pad the hex conversion with the appropriate number of leading zeroes. ... Save this answer. ... Show activity on this post. When converting a byte array to a hex array, we have to consider how they can be signed numbers. If so, we gotta convert them to decimal numbers first. More on stackoverflow.com
🌐 stackoverflow.com
node.js - How to convert a hex string to a byte and a byte to a hex string in Javascript? - Stack Overflow
backtohexstring decodes an incoming data string to the correct hex (I also used utf8 vs. byte, because it 'looked' like the incoming string when printed to the console), so I'm confused... I also found these two native javascript functions, the decoder works on my incoming stream, but I still ... More on stackoverflow.com
🌐 stackoverflow.com
javascript - How to convert an array of bytes into string with Node.js? - Stack Overflow
hmm.. maybe it is the promise library ... here: github.com/petkaantonov/bluebird/issues/34 ... var Promise = require("bluebird"); var crypto = Promise.promisifyAll(require("crypto")); crypto.randomBytesAsync(20).then(function(bytes){ console.log('random byte string:', bytes.toString("hex")); ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
GitHub
gist.github.com › amorri40 › 3430429
Javascript Byte to hex · GitHub
May 20, 2019 - Brilliant. This is just what I needed to solve a huge problem I was having! http://stackoverflow.com/questions/28706485/javascript-how-to-generate-rfc2898derivebytes-like-c
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 › 175 › bytes-to-hex-string › 4739 › js
Bytes to hex string, in JS
December 16, 2018 - (lambda (bytes &aux (size (* 2 (length bytes)))) (let ((hex (make-array size :element-type 'character :fill-pointer 0))) (prog1 hex (with-output-to-string (o hex) (map () (lambda (byte) (format o "~2,'0x" byte)) bytes)))))
🌐
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 string must: Have an even number of characters because two characters encode one byte. Only contain characters in the hexadecimal alphabet, which includes 0–9 and A–F (case-insensitive).
Find elsewhere
🌐
GitHub
gist.github.com › rodnt › d005e10042b481de2bf6d6c1c369fc49
Bytes to hex, string to bytes, bytes to string · GitHub
Bytes to hex, string to bytes, bytes to string · Raw · fridaUtils.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.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Uint8Array › toHex
Uint8Array.prototype.toHex() - JavaScript - MDN Web Docs
The toHex() method of Uint8Array instances returns a hex-encoded string based on the data in this Uint8Array object. This method creates strings from a byte array.
🌐
GitHub
gist.github.com › tanaikech › 707b2cd2705f665a11b1ceb2febae91e
Converting from String to Hex, from Hex to Bytes, from Bytes to String using Google Apps script · GitHub
This is a sample script for converting from the string value to the hex value, from the hex value to the byte array, from the byte array to the string value using Google Apps script.
🌐
GitHub
github.com › ricmoo › aes-js › blob › master › README.md
aes-js/README.md at master · ricmoo/aes-js
A pure JavaScript implementation of the AES block cipher algorithm and all common modes of operation (CBC, CFB, CTR, ECB and OFB). ... The utility functions have been renamed in the 3.x branch, since they were causing a great deal of confusion converting between bytes and string. The examples have also been updated to encode binary data as printable hex strings.
Author: ricmoo
🌐
GitHub
gist.github.com › shd101wyy › b49498a96715cf18b2776cc7ff8c4d95
string to hex, hex to string · GitHub
string to hex, hex to string · Raw · hex.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. Learn more about bidirectional Unicode characters ·
🌐
GitHub
github.com › orgs › espruino › discussions › 7597
string to hex string /hex string to string conversion · espruino · Discussion #7597
November 26, 2018 - // to hex data.split("").map(x=>(256+x.charCodeAt()).toString(16).substr(-2)).join("") // from hex E.toString("01020304102030".match(/../g).map(x=>parseInt(x,16))) This should be reasonably fast, but it'll allocate an array so for anything over a few hundred bytes it could cause problems. String append is actually pretty fast & efficient in Espruino, so using your idea with a few of the hacks from above you might find this is better:
🌐
Hex to String
hextostring.com › post › jshextostring
Convert Hex to String in JavaScript (Browser and Node) | Hex to String Guides
July 22, 2026 - function hexToAscii(hex) { const clean = hex.replace(/\s+/g, ""); let s = ""; for (let i = 0; i < clean.length; i += 2) { s += String.fromCharCode(parseInt(clean.slice(i, i + 2), 16)); } return s; } Fine for protocol bytes in the 0–127 range.
🌐
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). Overview What are hex strings and byte arrays? A hex...