简体   繁体   English

Javascript 将数字添加到 UInt8Array

[英]Javascript adding number to UInt8Array

I have a 2 byte number (0 to 65,536) which I want to add to a UInt8Array.我有一个 2 字节的数字(0 到 65,536),我想将它添加到 UInt8Array 中。 I can add a single byte number by directly referring to a index:我可以通过直接引用索引来添加单个字节数:

let bufarray = new Uint8Array(buffer);
bufarray[0] = 1;

But how can I add a 2 byte number to UInt8Array in Javascript/Typescript?但是如何在 Javascript/Typescript 中向 UInt8Array 添加一个 2 字节的数字?

You have to split your two byte number into two individual bytes.您必须将两个字节数拆分为两个单独的字节。 This can be done by bitwise shifting.这可以通过按位移位来完成。

 var twoBytes = 0xaaff; var byte1 = ((twoBytes >> 8) & 0xff); var byte2 = twoBytes & 0xff; console.log(byte1); console.log(byte2); var buffer = new ArrayBuffer(2); var Uint8View = new Uint8Array(buffer); Uint8View[0] = byte1; Uint8View[1] = byte2; var Uint16View = new Uint16Array(buffer); console.log(Uint16View[0]);

You can let the browser do the work for you:您可以让浏览器为您完成工作:

var array16 = new Uint16Array([49238])
var array8 = new Uint8Array(array16.buffer);

bufarray[0] = array8[0];
bufarray[1] = array8[1];

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

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