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.
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.
It's as simple as: Convert. ToBase64String(byte[]) and Convert. FromBase64String(string) to get byte[] back.
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.
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.
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')}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With