Skip to content

Instantly share code, notes, and snippets.

@NejcZdovc
Created March 26, 2018 09:22
Show Gist options
  • Save NejcZdovc/447d730e0aada3771da7b88804d010f2 to your computer and use it in GitHub Desktop.
Save NejcZdovc/447d730e0aada3771da7b88804d010f2 to your computer and use it in GitHub Desktop.
String to Uint8Array
// source https://coolaj86.com/articles/unicode-string-to-a-utf-8-typed-array-buffer-in-javascript/
'use strict';
// string to uint array
function unicodeStringToTypedArray(s) {
var escstr = encodeURIComponent(s);
var binstr = escstr.replace(/%([0-9A-F]{2})/g, function(match, p1) {
return String.fromCharCode('0x' + p1);
});
var ua = new Uint8Array(binstr.length);
Array.prototype.forEach.call(binstr, function (ch, i) {
ua[i] = ch.charCodeAt(0);
});
return ua;
}
unicodeStringToTypedArray('test')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment