最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Is Uint8ArrayUint16Array conversion broken in Firefox OS simulator? - Stack Overflow

programmeradmin0浏览0评论

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 plex data structures" in

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.

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 plex data structures" in https://developer.mozilla/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.

Share Improve this question edited Nov 5, 2013 at 2:51 nmaier 33.2k5 gold badges65 silver badges79 bronze badges asked Aug 28, 2013 at 1:33 MumpiHMumpiH 731 silver badge5 bronze badges 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. – Boris Zbarsky Commented Aug 28, 2013 at 2:43
Add a ment  | 

1 Answer 1

Reset to default 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]);
发布评论

评论列表(0)

  1. 暂无评论