Is Uint8Array / Uint16Array conversion broken in Firefox OS simulator?
Asked Answered
L

1

5

In case I'm just stupid, I'd be glad to her that. :)

Here is my code:

var t16 = new Uint16Array( new Uint8Array([1, 2, 3, 4]));
console.log(t16.BYTES_PER_ELEMENT);
for( var i = 0; i < t16.length; i++) 
    console.log(t16[i]);

And here is the output I got:

[02:56:32.197] 2
[02:56:32.197] 1
[02:56:32.197] 2
[02:56:32.197] 3
[02:56:32.197] 4

From the documentation I would expect:

2
513
1027

In the real project I'm using a tar library that delivers an ArrayBuffer containing 16-Bit data that I'd like to read, but I always get only access to the 8-Bit values.

Are my expectations wrong? At least that's how I read section "Working with complex data structures" in https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays

For the records: Firefox is 23.0.1, Java is Platform SE 7 U25 10.25.2.17 and Firefox OS simulator is 5.0pre3 on a W7/64 machine.

Lingle answered 28/8, 2013 at 1:33 Comment(1)
Note that you would only get 513 and 1027 (after fixing to pass the .buffer) on a little-endian machine. On a big-endian machine you would get 258 and 772.Medusa
J
8
var t8 = new Uint8Array([1, 2, 3, 4]),
    t16 = new Uint16Array(t8);

That way the Uint16Array constructor will treat the t8 like an ordinary array (just like Uint8Array does the array literal) and will construct a new array (buffer) to which the elements are copied.

To create an ArrayBufferView on the same ArrayBuffer, you will need to pass that buffer into the constructor:

var t8=new Uint8Array([1, 2, 3, 4]),
    t16 = new Uint16Array( t8.buffer );
//                           ^^^^^^^
console.log(t16.byteLength/t16.length); // or: t16.constructor.BYTES_PER_ELEMENT
for (var i = 0; i < t16.length; i++)
    console.log(t16[i]);
Johppah answered 28/8, 2013 at 1:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.