Search code examples
javascriptgnomegnome-shell-extensionsgjs

Convert String to UTF-16 Byte Array in GJS


In my Gnome Extension I would like to call GLib.convert. Sadly it does not work with strings but wants a ByteArray. Now I wonder how to convert a Javascript String into a UTF-16 Byte Array.

Bonus points if this uses some part of the Gnome bindings instead of implementing in Javascript.


Solution

  • ByteArray.fromString(someString, 'UTF-16') will convert your JS string into a UTF-16-encoded Uint8Array. This can be passed to GLib.convert (although, since fromString should understand all the encodings that GLib.convert does, maybe you don't need to after that?)

    See also the ByteArray documentation.