简体   繁体   English

Javascript 将 int 值转换为八位字节流数组

[英]Javascript Convert int value to octet stream Array

I want convert an integer (signed) to 32 bit (big endian) into a octet stream and give the octet stream as a array value to the constructor of a Buffer Object.我想将一个整数(有符号)转换为 32 位(大端)到一个八位字节流,并将八位字节流作为数组值提供给缓冲区对象的构造函数。

I can create it in the console for example for the value -2000:例如,我可以在控制台中为值 -2000 创建它:

<code>
buf = Buffer(4)
buf.writeInt32BE(-2000)
buf // is <Buffer ff ff f8 30>
buf1 = new Buffer([0xff, 0xff, 0xf8, 0x30])
</code>

The value -3000 is for example -3000 : 0xff ,0xff, 0xf4, 0x48值 -3000 例如 -3000 : 0xff ,0xff, 0xf4, 0x48

But the framework i use accepts not the writeInt32BE function and throws exception.但是我使用的框架不接受 writeInt32BE 函数并抛出异常。

How can i convert a 32 bit integer value signed to a octet Array stream without the writeInt32BE ?如何在没有 writeInt32BE 的情况下将有符号的 32 位整数值转换为八位字节数组流?

A function that takes a value and returns an array of octet stream.一个函数,它接受一个值并返回一个八位字节流数组。

Using a 4 byte array buffer, converted to a data view and calling setInt32 on the view seems to work.使用 4 字节数组缓冲区,转换为数据视图并在视图上调用 setInt32 似乎有效。 This approach supports specification of both little endian and big endian (the default) formats independent of machine architecture.这种方法支持独立于机器架构的小端和大端(默认)格式的规范。

function bigEnd32( value) {
    var buf = new ArrayBuffer(4);
    var view = new DataView(buf);
    view.setInt32( 0, value);
    return view;
}

// quick test (in a browser)
var n = prompt("Signed 32: ");
var view = bigEnd32( +n);
for(var i =  0 ; i < 4; ++i)
    console.log(view.getUint8( i));

Documentation was located searching for "MDN ArrayBuffer" "MDN Dataview" etc. Check out DataView in detail for properties that access the underlying array buffer - you may be able to tweak the code to suite your application.文档位于搜索“MDN ArrayBuffer”、“MDN Dataview”等的位置。详细查看DataView以获取访问底层数组缓冲区的属性 - 您可以调整代码以适应您的应用程序。

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

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