简体   繁体   English

如何在数组缓冲区中存储 32 位 integer?

[英]How to store a 32-bit integer in an arraybuffer?

I seem to not be understanding the Uint32Array .我似乎不理解Uint32Array According to what I've read about the Uint8Array I could just feed it a number inside an array ( Uint8Array([16]) or Uint8Array([96,56]) ) and the results are exactly that.根据我对Uint8Array的了解,我可以在数组( Uint8Array([16])Uint8Array([96,56]) )中输入一个数字,结果就是这样。 However, when I try the same thing for a larger number like Uint32Array([21640]) , it seems to truncate it.但是,当我对像Uint32Array([21640])这样的较大数字尝试相同的操作时,它似乎会截断它。 Where 21640 should equal 5488 in hex, I only get 88. How does this actually work? 21640 应该等于十六进制的 5488,我只得到 88。这实际上是如何工作的?

Edit: Elaborations编辑:阐述

I am also attempting to concatenate several ArrayBuffers together.我也试图将几个 ArrayBuffers 连接在一起。 If I'm not mistaken readAsArrayBuffer produces an Uint8Array , and I am trying to append to that some 32-bit numbers using https://gist.github.com/72lions/4528834如果我没记错readAsArrayBuffer产生一个Uint8Array ,我正在尝试 append 使用https://gist.ZBF215181B514052452488/452488/454488/721B6到一些 32 位数字。

There is so much information and examples on Uint8Array and what little there was on Uint32Array makes me think that one of these 32 would store a value as if it was 4 of the 8.关于Uint8Array的信息和示例太多了,而Uint32Array上的信息很少,让我认为这 32 个中的一个会存储一个值,就好像它是 8 个中的 4 个一样。

The largest value of an unsigned 8 bit number is 255. Larger numbers will be truncated or rolled over depending on the os/cpu.无符号 8 位数字的最大值是 255。更大的数字将被截断或翻转,具体取决于 os/cpu。 If you want to convert a 32 bit numbers in an 8 bit array try something like this.如果您想在 8 位数组中转换 32 位数字,请尝试这样的操作。

var number = 21640;
var byte1 = 0xff & number;
var byte2 = 0xff & (number >> 8);
var byte3 = 0xff & (number >> 16);
var byte4 = 0xff & (number >> 24);

var arr1 = Uint8Array([byte1,byte2,byte3,byte4]);

Just reverse the order of the bytes when you create the array depending on if you want little or big endian.创建数组时只需颠倒字节顺序,具体取决于您想要小端还是大端。

Here is a working example showing 5488 in console这是一个在控制台中显示 5488 的工作示例

    var bigNumber = new Uint32Array([21640]);
    console.log(bigNumber[0].toString(16));

Since you've added more to the question.由于您在问题中添加了更多内容。 If you wanted to convert如果你想转换

var byte1 = 0x88;
var byte2 = 0x54;
var byte3 = 0;
var byte4 = 0;

var bigValue = (byte4 << 24) | (byte3 << 16) | (byte2 << 8) | (byte1);

console.log(bigValue);

Although you will need to factor in Endianness尽管您需要考虑字节顺序

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM