Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert array of byte values to base64 encoded string and break long lines, Javascript (code golf)

This JavaScript function takes an array of numbers (in the range 0-255) and converts to a base64-encoded string, then breaks long lines if necessary:

function encode(data)
{
  var str = "";
  for (var i = 0; i < data.length; i++)
    str += String.fromCharCode(data[i]);

  return btoa(str).split(/(.{75})/).join("\n").replace(/\n+/g, "\n").trim();
}

Can you do the same thing in less code? Can you do it so it runs faster? Portability no object, use brand new language features if you want, but 's gotta be in JavaScript.

like image 806
zwol Avatar asked Mar 20 '11 04:03

zwol


People also ask

Can base64 have line breaks?

Because line breaks are considered white-space characters in a base-64 encoding, they are ignored when converting a base-64 encoded string back to a byte array.

How do I convert a byte array to base64 in Java?

It's as simple as: Convert. ToBase64String(byte[]) and Convert. FromBase64String(string) to get byte[] back.

What is base64binary?

The base64 is a binary to a text encoding scheme that represents binary data in an ASCII string format. base64 is designed to carry data stored in binary format across the channels. It takes any form of data and transforms it into a long string of plain text.

How do you convert a string to base64?

To convert a string into a Base64 character the following steps should be followed: Get the ASCII value of each character in the string. Compute the 8-bit binary equivalent of the ASCII values. Convert the 8-bit characters chunk into chunks of 6 bits by re-grouping the digits.


1 Answers

I have another entry:

function encode(data)
{
    var str = String.fromCharCode.apply(null,data);
    return btoa(str).replace(/.{76}(?=.)/g,'$&\n');
}

Minified, 88 characters:

function e(d){return btoa(String.fromCharCode.apply(d,d)).replace(/.{76}(?=.)/g,'$&\n')}

Or if you want trailing newlines, 85 characters:

function e(d){return btoa(String.fromCharCode.apply(d,d)).replace(/.{1,76}/g,'$&\n')}
like image 186
Anomie Avatar answered Nov 15 '22 06:11

Anomie