Uint16Array访问byteOffset 1,3,5等

时间:2011-12-10 10:08:40

标签: javascript firefox opera typed-arrays

new Uint16Array(ArrayBuffer, byteOffset, length);

对于Uint16(单词)byteOffset只能是0,2,4,6等。如何访问第2个,第4个字节? (byteOffset = 1,3等) DataView是Chrome的解决方案,但不适用于FireFox(根本不了解Opera)。

1 个答案:

答案 0 :(得分:2)

您可以将缓冲区转换为Uint8Array(对于单独的字节),然后从该数组中读取:

var a = new Uint16Array(10);

// fill `a` with data
for(var i = 0; i < 10; i++) a[i] = i * 10;

var b = new Uint8Array(a.buffer); // `b` contains bytes of `a`, e.g. use `b[1]`

var orig = new Uint8Array(buffer);

var sub = new Uint16Array(orig.subarray(1, 2)); // from index 1 to 2, so second byte

var word = sub[0]; // 2nd byte as Uint16

关于您发布的案例:

var buf = new ArrayBuffer(65535);
var u8s = new Uint8Array(buf);
u8s[0] = 0x01;
u8s[1] = 0x02;
u8s[2] = 0x03;
var x = new Uint8Array(u8s.subarray(1, 3)).buffer; // buffer from subarray
                                                   // 1 to 3 because 1 word is 2 bytes
sub = new Uint16Array(x); // create Uint16Array from it
sub[0]; // 770, which is:   (3 << 8) | 2   (it is big-endian)