10

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?

asked Jun 2, 2016 at 15:57
1

4 Answers 4

15

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

answered Jun 2, 2016 at 16:09
Sign up to request clarification or add additional context in comments.

1 Comment

I used this to convert a utf8 string (nodejs's default encoding in most cases), into utf16 string (which is the type of default encoding for javascript strings).
2
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)
answered Mar 23, 2017 at 19:56

Comments

2

I needed to convert a utf8 encoded string to a hexadecimal utf-16 string:

function dec2hex(dec, padding){
 return parseInt(dec, 10).toString(16).padStart(padding, '0');
}
function utf8StringToUtf16String(str) {
 var utf16 = [];
 for (var i=0, strLen=str.length; i < strLen; i++) {
 utf16.push(dec2hex(str.charCodeAt(i), 4));
 }
 return utf16.join();
}
answered Dec 23, 2018 at 8:24

Comments

0

To get Uint8Array, use this code

inspired by shilch's Answer

change return bufView to return new Uint8Array(buf)


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 new Uint8Array(buf);
}
var arr = strEncodeUTF16('13,56ドル');
answered Aug 31, 2018 at 6:43

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.