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();
}
🌐
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 - 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.
🌐
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 ]
🌐
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;
🌐
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....
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() ...
🌐
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
🌐
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); ...
🌐
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.
🌐
Hex to String
hextostring.com › post › jshextostring
Convert Hex to String in JavaScript (Browser and Node) | Hex to String Guides
July 22, 2026 - const hex = "48656c6c6f"; const text = Buffer.from(hex, "hex").toString("utf8"); console.log(text); // Hello // string → hex console.log(Buffer.from("Hello", "utf8").toString("hex")); Odd-length hex throws in modern Node. Prefer failing loudly over padding. function hexToBytes(hex) { const clean = hex.replace(/\s+/g, "").replace(/^0x/i, ""); if (clean.length % 2) throw new Error("hex length must be even"); if (!/^[0-9a-fA-F]*$/.test(clean)) throw new Error("invalid hex"); const out = new Uint8Array(clean.length / 2); for (let i = 0; i < clean.length; i += 2) { out[i / 2] = parseInt(clean.slice(i, i + 2), 16); } return out; } function hexToString(hex, encoding = "utf-8") { return new TextDecoder(encoding).decode(hexToBytes(hex)); } console.log(hexToString("e4bda0e5a5bd")); // 你好
🌐
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 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();
}
🌐
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.
🌐
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 ...