Uint8Array to string in Javascript

ID : 20090

viewed : 17

Tags : javascriptjavascript

Top 5 Answer for Uint8Array to string in Javascript

vote vote

95

TextEncoder and TextDecoder from the Encoding standard, which is polyfilled by the stringencoding library, converts between strings and ArrayBuffers:

var uint8array = new TextEncoder().encode("ยข"); var string = new TextDecoder().decode(uint8array); 
vote vote

84

This should work:

// http://www.onicos.com/staff/iz/amuse/javascript/expert/utf.txt  /* utf.js - UTF-8 <=> UTF-16 convertion  *  * Copyright (C) 1999 Masanao Izumo <iz@onicos.co.jp>  * Version: 1.0  * LastModified: Dec 25 1999  * This library is free.  You can redistribute it and/or modify it.  */  function Utf8ArrayToStr(array) {     var out, i, len, c;     var char2, char3;      out = "";     len = array.length;     i = 0;     while(i < len) {     c = array[i++];     switch(c >> 4)     {        case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7:         // 0xxxxxxx         out += String.fromCharCode(c);         break;       case 12: case 13:         // 110x xxxx   10xx xxxx         char2 = array[i++];         out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F));         break;       case 14:         // 1110 xxxx  10xx xxxx  10xx xxxx         char2 = array[i++];         char3 = array[i++];         out += String.fromCharCode(((c & 0x0F) << 12) |                        ((char2 & 0x3F) << 6) |                        ((char3 & 0x3F) << 0));         break;     }     }      return out; } 

It's somewhat cleaner as the other solutions because it doesn't use any hacks nor depends on Browser JS functions, e.g. works also in other JS environments.

Check out the JSFiddle demo.

Also see the related questions: here and here

vote vote

75

Here's what I use:

var str = String.fromCharCode.apply(null, uint8Arr); 
vote vote

64

vote vote

60

Found in one of the Chrome sample applications, although this is meant for larger blocks of data where you're okay with an asynchronous conversion.

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

Top 3 video Explaining Uint8Array to string in Javascript

Related QUESTION?