How to convert an Uint8Array to string in Javascript

By FoxLearn 2/27/2025 2:32:52 AM   21
To convert a Uint8Array to a string in JavaScript, you can use several methods depending on the environment (e.g., browser or Node.js) and the size of the data.

A Uint8Array is a typed array that stores 8-bit unsigned integers, and you might need to convert it to a regular string.

1. For Small Arrays

This method is acceptable for smaller arrays (less than 100k characters).

However, be cautious, as larger arrays may cause exceptions like RangeError: Maximum call stack size exceeded or Out of stack space. Additionally, this method does not handle UTF-8 characters well.

function uint8ArrayToString(uint8Array) {
  return String.fromCharCode.apply(null, uint8Array);
}

// Example usage
const uint8Arr = new Uint8Array([72, 101, 108, 108, 111]); // Represents "Hello"
console.log(uint8ArrayToString(uint8Arr)); // Output: "Hello"

2. Browser Implementation

If your JavaScript is running in a browser, you can leverage the TextEncoder and TextDecoder functions from the native Encoding API, which allows you to specify the encoding type.

/**
 * Convert a Uint8Array into a string.
 *
 * @returns {String}
 */
function Decodeuint8arr(uint8array) {
    return new TextDecoder("utf-8").decode(uint8array);
}

/**
 * Convert a string into a Uint8Array.
 *
 * @returns {Uint8Array}
 */
function Encodeuint8arr(myString) {
    return new TextEncoder("utf-8").encode(myString);
}

// Example usage
const str = "Hello";
const uint8Arr = stringToUint8Array(str);
console.log(uint8Arr); // Output: Uint8Array [72, 101, 108, 108, 111]

3. Cross-Platform Method

This method works across different JavaScript environments (including non-browser environments) and follows the UTF-8 convention. It doesn't rely on any browser-specific functions, making it versatile.

/* utf.js - UTF-8 <=> UTF-16 conversion
 * Copyright (C) 1999 Masanao Izumo <[email protected]>
 * Version: 1.0
 * LastModified: Dec 25 1999
 */

function Utf8ArrayToStr(array) {
    var out = "";
    var len = array.length;
    var i = 0;
    while (i < len) {
        var c = array[i++];
        switch (c >> 4) { 
            case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7:
                out += String.fromCharCode(c);
                break;
            case 12: case 13:
                var char2 = array[i++];
                out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F));
                break;
            case 14:
                var char2 = array[i++];
                var char3 = array[i++];
                out += String.fromCharCode(((c & 0x0F) << 12) |
                           ((char2 & 0x3F) << 6) |
                           ((char3 & 0x3F) << 0));
                break;
        }
    }
    return out;
}

// Example usage
const uint8Arr = new Uint8Array([72, 101, 108, 108, 111]); // Represents "Hello"
console.log(uint8ArrayToStringUtf8(uint8Arr)); // Output: "Hello"

4. For Large Data Blocks

When dealing with large datasets, you may want to use an asynchronous method to handle the conversion. This method creates a Blob from the Uint8Array and then uses a FileReader to read it as text.

/**
 * Converts a Uint8Array to a string asynchronously.
 *
 * @param {Uint8Array} uint8arr - The buffer to convert.
 * @param {Function} callback - The function to call when conversion is complete.
 */
function largeUint8ArrToString(uint8arr, callback) {
    var bb = new Blob([uint8arr]);
    var f = new FileReader();
    f.onload = function(e) {
        callback(e.target.result);
    };
    
    f.readAsText(bb);
}

// Example usage:
var myUint8Arr = new Uint8Array([72, 101, 108, 108, 111, 32, 33]);

largeUint8ArrToString(myUint8Arr, function(text) {
    console.log(text);  // "Hello"
});

Note: This asynchronous method is particularly useful when working with large datasets, as it prevents blocking the main thread.