我一直在努力研究如何在JavaScript中使用类型数组,但是我还没有点击。我不明白如何正确地读/写“视图”。
var a = 23453.342;
现在假设我想将它存储在Float64Array类型数组
中view[0] = ??? //how do I copy the bytes that represent variable a into here.
另外,假设我想将内部JavaScript中的整数123456存储为64位浮点数:
var i = 123456;
但我想将它存储为好像它实际上是一个4字节的整数。
var buff = new ArrayBuffer(4);
var view = new UInt32Array(buff);
view[0] = ???; //how do i determine and write the 4 bytes that would represent the value of i.
然后在这两种情况下,一旦我能够写入数据,我如何将其读回到JavaScript中的局部变量。
答案 0 :(得分:5)
如果你的值小于Typed Array单元而不是将值存储到数组中,例如你有 23453.342 并使用Float64,那么只需将它放入数组
In [8]: A = np.random.rand(3000)
In [9]: B = np.random.rand(2000)
In [10]: %timeit ((A[:, None] - B) ** 2).sum(0) # @Psidom's soln
10 loops, best of 3: 21 ms per loop
In [11]: %timeit einsum_based(A,B)
100 loops, best of 3: 12.3 ms per loop
现在,如果您想将数字转换为单个字节,例如32位数字并获得4个字节,则可以使用两个TypedArray视图。将您的值放入较高位数组,并从较低的单元数组中读取字节。
var view = new Float64Array(1);
view[0] = 23453.342;

如果要手动获取字节,或者无法访问更高单元类型的数组,那么可以使用位移和按位AND运算符来获取单个字节
//The argument passed to ArrayBuffer constructor
//is number of Bytes the buffer should be
var buff = new ArrayBuffer(4);
//Since buffer was made for 4 bytes, this view can read/store 1 32bit value
var view = new Uint32Array(buff);
//buffer still has 4 bytes, so this view can read/store 4 8bit values
var view2 = new Uint8Array(buff);
view[0] = 123456;
console.log(view2);

至于将值取回,在使用两个类型数组的情况下,您只需读取目标单元的数组。在这种情况下,请阅读Uint32Array
var i = 123456;
var buff = new ArrayBuffer(4);
var view = new Uint32Array(buff);
var view2 = new Uint8Array(buff);
view2[0] = i & 0x000000FF;
view2[1] = (i & 0x0000FF00) >> 8;
view2[2] = (i & 0x00FF0000) >> 16;
view2[3] = (i & 0xFF000000) >> 24;
console.log( view2, view[0] );

再次,如果你想使用位移方式,你需要从较小的类型数组中移位每个字节,并将它们按位或一起移位。
var buff = new ArrayBuffer(4);
var view = new Uint32Array(buff);
var view2 = new Uint8Array(buff);
view2[0] = 64, view2[1] = 226, view2[2] = 1, view2[3] = 0;
var i = view[0];
console.log(i);

答案 1 :(得分:1)
当您创建某种类型的TypedArray
时,请说Int8Array
,如下所示:
let my = new Int8Array(1);
并为其指定一个值,如下所示:
my[0] = 123456;
执行基于转换的on the this table。因此,对于Int8Array
,方法ToInt8用于最后的步骤:
...
设int8bit为int modulo 2 ^ 8 如果int8bit≥2^ 7,则返回int8bit - 2 ^ 8,否则返回int8bit。
所以,如果我们运行这些步骤
Let int8bit be 123456 modulo 2^8 // 64
64 < 2^7 -> return int8bit, which is 64
所以64
是你应该期待的:
console.log(my[0]); // 64
如果您对实际位顺序感兴趣,请查看this answer以获取算法或本文details of floating point。