Caio Keto Caio Keto - 5 months ago 483
Javascript Question

How to convert uint8 Array to base64 Encoded String?

I got a webSocket comunication, I recieve base64 encoded string, convert it to uint8 and work on it, but now I need to send back, I got the uint8 array, and need to convert it to base64 string, so I can send it.
How can I make this convertion?


To base64 encode a Uint8Array:

var u8 = new Uint8Array([65, 66, 67, 68]);
var b64encoded = btoa(String.fromCharCode.apply(null, u8));

And to decode the base64 string back to a Uint8Array:

var u8_2 = new Uint8Array(atob(b64encoded).split("").map(function(c) {
    return c.charCodeAt(0); }));


Mozilla recently released a StringView for manipulating strings contained in Typed Arrays. Specifically the bytesToBase64 method is probably what you want.

If that's too heavy weight, then here is a simple routine (based on the one posted by @RohitSengar) that converts a Uint8Array to a string (which can then be easily base64 encoded):

function Uint8ToString(u8a){
  var CHUNK_SZ = 0x8000;
  var c = [];
  for (var i=0; i < u8a.length; i+=CHUNK_SZ) {
    c.push(String.fromCharCode.apply(null, u8a.subarray(i, i+CHUNK_SZ)));
  return c.join("");
// Usage
var u8 = new Uint8Array([65, 66, 67, 68]);
var b64encoded = btoa(Uint8ToString(u8));