Search code examples
javascripttype-conversionuint8t

Dealing with uint8_t in javascript


G'day peoples,

I'm using MavLink to obtain GPS information. One of the message types is GPS_STATUS which is described by MavLink using a series of uint8_t[20].

If I run the following code:

console.log(' sat prn: ' + message.satellite_prn);
console.log(' sat prn: ' + JSON.stringify(message.satellite_prn));
console.log(' sat prn: ' + JSON.stringify(new Uint8Array(message.satellite_prn)));

I get the following output:

 sat prn: <weird charcaters...>
 sat prn: "\u0002\u0005\n\f\u000f\u0012\u0015\u0019\u001a\u001b\u001d\u001e\u001f\u0000\u0000\u0000\u0000"
 sat prn: {"BYTES_PER_ELEMENT":1,"buffer":{"byteLength":0},"length":0,"byteOffset":0,"byteLength":0}

So obviously it's not working. I need a means to get the int value of each element.

I found this https://developer.mozilla.org/en-US/docs/JavaScript/Typed_arrays?redirectlocale=en-US&redirectslug=JavaScript_typed_arrays

Which made me think I would be able to do the following:

satellite_prn = Array.apply([], new Uint8Array(message.satellite_prn));
satellite_prn.length === 20;
satellite_prn.constructor === Array;

But when I stringify it via JSON it reports [], I presume this is an empty array.

Anyone know how I can do this? I know that the data is an array of 20 unsigned 8 bit integers. I just need to know how to access or parse them.

Note: I'm using node.js, but that shouldn't affect what I'm doing. This is why I'm using console.log, as it's avail in node.js.


Solution

  • Two issues with your code:

    1. message.satellite_prn is a string not an array
    2. Unit8Array needs to be loaded with .set

    To get an array of numbers from message.satellite_prn, do this:

    var array = message.satellite_prn.map(function(c) { return c.charCodeAt(0) })
    

    To load an ArrayBuffer, do this:

    var buffer = new ArrayBuffer(array.length);
    var uint8View = new Uint8Array(buffer);
    uint8View.set(array);
    

    Ideally you wouldn't need to go through the string. If you are obtaining the data from an up-to-date implementation of XMLHttpRequest, such as xhr2, you can set:

    responseType = "arraybuffer"