Monday, June 3, 2024
102
rated 0 times [  103] [ 1]  / answers: 1 / hits: 18703  / 14 Years ago, sun, march 20, 2011, 12:00:00

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.


More From » firefox-addon

 Answers
30

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')}

[#93179] Friday, March 18, 2011, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
taliac

Total Points: 84
Total Questions: 114
Total Answers: 114

Location: Morocco
Member since Fri, May 22, 2020
4 Years ago
taliac questions
Sun, Mar 21, 21, 00:00, 3 Years ago
Tue, May 12, 20, 00:00, 4 Years ago
Mon, Jan 13, 20, 00:00, 4 Years ago
;