Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conversion between UTF-8 ArrayBuffer and String

I have an ArrayBuffer which contains a string encoded using UTF-8 and I can't find a standard way of converting such ArrayBuffer into a JS String (which I understand is encoded using UTF-16).

I've seen this code in numerous places, but I fail to see how it would work with any UTF-8 code points that are longer than 1 byte.

return String.fromCharCode.apply(null, new Uint8Array(data)); 

Similarly, I can't find a standard way of converting from a String to a UTF-8 encoded ArrayBuffer.

like image 564
Tom Leese Avatar asked Jun 19 '13 13:06

Tom Leese


People also ask

Is ArrayBuffer same as buffer?

The ArrayBuffer object is used to represent a generic, fixed-length raw binary data buffer. It is an array of bytes, often referred to in other languages as a "byte array".

What UTF 8 means?

UTF-8 (UCS Transformation Format 8) is the World Wide Web's most common character encoding. Each character is represented by one to four bytes. UTF-8 is backward-compatible with ASCII and can represent any standard Unicode character.


1 Answers

Using TextEncoder and TextDecoder

var uint8array = new TextEncoder("utf-8").encode("Plain Text"); var string = new TextDecoder().decode(uint8array); console.log(uint8array ,string ) 
like image 163
PPB Avatar answered Sep 21 '22 05:09

PPB