[quickjs-devel] Re: Strings, binary data and UTF-8

  • From: John Gardner <gardnerjohng@xxxxxxxxx>
  • To: quickjs-devel@xxxxxxxxxxxxx
  • Date: Thu, 6 Aug 2020 04:40:25 +1000


Strings in JS are unicode.


To clarify—and offer a slight correction—strings in JavaScript are *UTF-16*
encoded,

Strictly speaking, there's no such thing as "Unicode-encoded text", because
Unicode isn't a character encoding.

On Thu, 6 Aug 2020 at 03:01, Ondřej Jirman <deibeemoocheuguhumoh@xxxxxx>
wrote:

Hi,

On Wed, Aug 05, 2020 at 08:46:58PM +0400, Дмитрий Фролов wrote:
Hello!

I'm writing simple UDP client and server app. I'm trying to send binary
data stored in js string to UDP socket.
I used JS_ToCString function, but it interprets binary data in my string
as
UTF-8 symbols and tries to decode it.
Assume, I want to send 6 bytes binary string composed with
String.fromCharCode() in js: 06 07 fa 00 00 e0.
In C from JS_ToCString function I've got string with 3-rd byte replaced:
06
07 c3 ba 00 00.

So instead of
  >>  data = JS_ToCString(ctx, argv[3]);
 I have to use
  >>  JSString *str = JS_VALUE_GET_STRING(argv[3]);
  >>  data = (char *) &str->u.str8;

JSString is declared in quickjs.c, not in quickjs.h, and I have to copy
it's declaration.

The same thing with receiving data from UDP socket: instead of
JS_NewStringLen() I have to use js_new_string8().

So my question: Is there a better way of getting raw data from js string
without UTF-8 decoding?

Use ArrayBuffer for binary data. Strings in JS are unicode.

regards,
        o.

Thanks


Other related posts: