/* # String to ArrayBuffer Conversion #
Uint8Array (short) => *1 => each char. 1 byte
Uint16Array (medium) => *2 => each char. 2 bytes
Uint32Array (long) => *4 => each char. 4 bytes
JSON => JSON.stringify({data: 'Hello World!'});
*/
var string = 'Hello World!';
var buffer = new ArrayBuffer(string.length*2);
var bufferView = new Uint16Array(buffer);
for (var i = 0; i < string.length; i++) {
bufferView[i] = string.charCodeAt(i);
}
console.log(bufferView);
/* # ArrayBuffer to String Conversion #
alternative to 'bufferView' => new Uint16Array(buffer)
JSON => JSON.parse(_string).data
*/
var _string = String.fromCharCode.apply(null, bufferView);
console.log(_string);
/* As individual functions
function str2arr(str, callback) {
var array = new ArrayBuffer(str.length);
var bufferView = new Uint8Array(array);
for (var i = 0; i < str.length; i++) {
bufferView[i] = str.charCodeAt(i);
}
callback(bufferView);
}
function arr2str(arr, callback) {
var _arr = String.fromCharCode.apply(null, arr);
callback(_arr);
}
*/
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Fiddle Pages
Your fiddles accessible under a custom domain and a vanity path - the simplest hosting for your personal project.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Get Fiddle Pages with PRO
Your fiddles accessible under a custom domain and a vanity path - the simplest hosting for your personal project.