gpt4 book ai didi

javascript - 偏移量在 DataView 的范围之外,调试器显示它在范围内

转载 作者:行者123 更新时间:2023-12-04 12:33:47 24 4
gpt4 key购买 nike

我收到错误 Offset is outside the bounds of the DataView对于以下代码

let data = [...] // some array of Int16
let buf = new ArrayBuffer(data.length);
let dataView = new DataView(buf);

data.forEach((b, i) => {
dataView.setInt16(i, b);
});
这是 Chrome 中的调试 View
enter image description here
你可以看到 i47999和我的 DataView 的缓冲区大小是 48000 .我在这里想念什么?

最佳答案

这是因为 Int16Array 每个元素有 2 个字节。所以它的 .length 将比它的缓冲区的实际大小小两倍,使用它的 .byteLength 来创建一个相同大小的新 ArrayBuffer。
此外,设置 int16 实际上会一次设置两个字节。
所以在某些时候,你的循环会尝试设置一个不存在的字节,它会抛出那个错误。
但这并不是您的代码的全部。由于 forEach() 的迭代值 i 是基于 TypedArray 的 .length 值,因此您还需要将其乘以 TypedArray 每个元素的字节数以在 DataView.setInt16 中设置正确的偏移量。

const data = new Int16Array( [ 0xFFFF, 0xFF00, 0x00FF, 0x000 ] );

console.log( "length:", data.length );
console.log( "byteLength:", data.byteLength );

const buf = new ArrayBuffer(data.byteLength);
const dataView = new DataView(buf);

data.forEach( (b, i) => {
dataView.setInt16( i * data.BYTES_PER_ELEMENT, b );
} );
console.log( new Int16Array( buf ) );
// -1, 255, -256, 0

现在,我不确定你想用这个片段做什么,但是要复制你的 TypedArray,那么你必须检查计算机的字节顺序,然后使用 DataView.setInt16( byteOffset, value, littleEndian ) 的第三个参数,但是你也可以简单地做:

const data = new Int16Array( [ 0xFFFF, 0xFF00, 0x00FF, 0x000 ] );
const buf = data.buffer.slice();

// ensure they are not the same ArrayBuffer
data.fill( 0 );
console.log( "data: ", data ); // 0, 0, 0 ,0
console.log( "copy:", new Int16Array( buf ) );
// -1, 256, 255, 0

如果你想从小端交换到大端,那么你也可以通过首先检查计算机的字节序并在必要时使用 .map 交换值来比使用 DataView 更快。

const data = new Int16Array( [ 0xFFFF, 0xFF00, 0x00FF, 0x000 ] );
// check for the computer's endianness
const is_little_endian = new Uint8Array( new Uint32Array( [ 0x12345678 ] ).buffer )[ 0 ] === 0x78;
console.log( is_little_endian );

const buf = is_little_endian ?
data.map( (val) => (val<<8) | (val>>8) & 0xFF ).buffer : data.buffer.slice();

// ensure they are not the same ArrayBuffer
data.fill( 0 );
console.log( "data: ", data ); // 0, 0, 0 ,0
console.log( "copy:", new Int16Array( buf ) );
// -1, 255, -256, 0

关于javascript - 偏移量在 DataView 的范围之外,调试器显示它在范围内,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63466278/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com