简体   繁体   中英

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.

I can create it in the console for example for the value -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

But the framework i use accepts not the writeInt32BE function and throws exception.

How can i convert a 32 bit integer value signed to a octet Array stream without the writeInt32BE ?

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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