Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I encode a JavaScript string in utf-16?

In Python 3, I can do this:

>>> "€13,56".encode('utf-16')
b'\xff\xfe\xac 1\x003\x00,\x005\x006\x00'

The input is a (unicode) string, while the output is a sequence of raw bytes of that string encoded in utf-16.

How can I do the same in JavaScript - go from a (unicode) string, to a sequence of raw bytes (perhaps as a Uint8Array?) of that string encoded in utf-16?

like image 487
Claudiu Avatar asked Jun 02 '16 15:06

Claudiu


2 Answers

Do you want this?

function strEncodeUTF16(str) {
  var buf = new ArrayBuffer(str.length*2);
  var bufView = new Uint16Array(buf);
  for (var i=0, strLen=str.length; i < strLen; i++) {
    bufView[i] = str.charCodeAt(i);
  }
  return bufView;
}

var arr = strEncodeUTF16('€13,56');

Taken from Google Developers

like image 84
shilch Avatar answered Oct 19 '22 11:10

shilch


function strEncodeUTF16(str) {
  var arr = []
  for (var i = 0; i < str.length; i++) {
    arr[i] = str.charCodeAt(i)
  }
  return arr
}


var arr = strEncodeUTF16('€13,56');

console.log(arr)
like image 33
alsotang Avatar answered Oct 19 '22 11:10

alsotang