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
🌐
Prussiafan
prussiafan.club › posts › hex-to-bytes-and-back
Hex to Bytes and Back - prussiafan.club
September 15, 2023 - Part of this is because I do a lot of stuff related to cryptography and cryptocurrency (which, no surprise, is basically just more cryptography), which involves tons of work with bytes and often, converting them to hex for storage or display. The other part is because Javascript doesn't have a builtin way to convert hex to bytes or the other way around (Node.js apparently has Buffer.from but I never use that), and also because I just like writing things from scratch, which you may notice is a common theme in this blog.
🌐
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.
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
byte[] a = new byte[s.Length/2]; for (int i = 0, h = 0; h < s.Length; i++, h += 2) { a[i] = (byte) Int32.Parse(s.Substring(h, 2), System.Globalization.NumberStyles.HexNumber); } import std.algorithms; import std.array; import std.conv; import std.range; ubyte[] a = s.chunks(2) .map!(digits => digits.to!ubyte) .array;
🌐
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-a-hex-string-to-a-byte-and-a-byte-to-a-hex-string-in-javascript
How to Convert Hex Strings to Bytes and Bytes to Hex Strings in JavaScript: Troubleshooting Common Issues with Native Functions — xjavascript.com
Hexadecimal (hex) strings and byte ... between hex strings and bytes, developers can leverage native methods (e.g., `parseInt`, `map`, `toString`) to implement these conversions....
🌐
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 - const hexString = "cafed00d"; const bytes = Uint8Array.fromHex(hexString); console.log(bytes); // Uint8Array [ 202, 254, 208, 13 ]
Find elsewhere
🌐
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. To convert the string into a single number, use the parseInt() ...
🌐
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; ...
🌐
Stack Overflow
stackoverflow.com › questions › 46044614 › convert-hex-coding-to-bytes › 46045100
javascript - Convert Hex coding to Bytes - Stack Overflow
I have this coding: *(uint32_t*) 0xFFFFFFFF8269C07Cull=0; *(uint32_t*) 0xFFFFFFFF8269B56Full=0; And I want to convert this to something similar to: function doWrite(write) { setBase(write); ...
🌐
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
🌐
MeasureThat
measurethat.net › Benchmarks › Show › 107 › 4 › parse-hex-to-bytes
Benchmark: parse hex to bytes - MeasureThat.net
parse hex-string to 'bytes like object' (Uint8Array) in javascript · Random hex string generation benchmark · array buffer to hex conversion · Comments · × · Do you really want to delete benchmark? Cancel Delete · × · FAQ: FAQ · Source code: GitHub/MeasureThat.net ·
🌐
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
🌐
DEV Community
dev.to › taniarascia › understanding-bits-bytes-bases-and-writing-a-hex-dump-in-javascript-l6f
Understanding Bits, Bytes, Bases, and Writing a Hex Dump in JavaScript - DEV Community
May 30, 2019 - If you do decide to open it anyway, you'll probably see what appears to be a question mark. Fortunately, we can view the raw contents with hexdump. 00000000 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f |................| 00000010 · As you can see, unprintable ASCII characters are represented by a ., and the bytes are confirmed hexadecimal.
🌐
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
Even length: Valid hex strings must have an even number of characters (each byte = 2 hex chars). Case insensitivity: Characters A-F and a-f are equivalent (e.g., "a3" = "A3"). Whitespace sensitivity: Spaces or newlines are not valid unless ...
🌐
GitHub
gist.github.com › tanaikech › 707b2cd2705f665a11b1ceb2febae91e
Converting from String to Hex, from Hex to Bytes, from Bytes to String using Google Apps script · GitHub
const str = "sample string"; // This is a original string value. // Convert string to hex. const hexFromStr = Utilities.newBlob(str) .getBytes() .map((byte) => ("0" + (byte & 0xff).toString(16)).slice(-2)) .join(""); console.log(hexFromStr); // <--- 73616d706c6520737472696e67 // Convert hex to bytes.