How to add bytes, multibytes and buffer in ArrayBuffer in javascript?

Javascript ArrayBuffer or TypedArrays do not have any appendByte (), appendBytes (), or appendBuffer () methods. So, if I want to populate one ArrayBuffer value at a time, how do I do this?

var firstVal = 0xAB; // 1 byte var secondVal = 0x3D7F // 2 bytes var anotherUint8Array = someArr; var buffer = new ArrayBuffer(); // I don't know the length yet var bufferArr = new UInt8Array(buffer); // following methods do not exist. What are the alternatives for each?? bufferArr.appendByte(firstVal); bufferArr.appendBytes(secondVal); bufferArr.appendBuffer(anotherUint8Array); 
+7
javascript buffer arraybuffer typed-arrays
source share
2 answers

You can create a new TypedArray with a new ArrayBuffer, but you cannot resize an existing buffer

 function concatTypedArrays(a, b) { // a, b TypedArray of same type var c = new (a.constructor)(a.length + b.length); c.set(a, 0); c.set(b, a.length); return c; } 

Can now do

 var a = new Uint8Array(2), b = new Uint8Array(3); a[0] = 1; a[1] = 2; b[0] = 3; b[1] = 4; concatTypedArrays(a, b); // [1, 2, 3, 4, 0] Uint8Array length 5 

If you want to use different types, go through Uint8Array , since the smallest unit is a byte, i.e.

 function concatBuffers(a, b) { return concatTypedArrays( new Uint8Array(a.buffer || a), new Uint8Array(b.buffer || b) ).buffer; } 

This means that .length will work as expected, now you can convert it to your typed array (make sure it is the type that will accept .byteLength in the buffer, though)


Now you can implement any method that you like to concatenate your data, for example.

 function concatBytes(ui8a, byte) { var b = new Uint8Array(1); b[0] = byte; return concatTypedArrays(ui8a, b); } var u8 = new Uint8Array(0); u8 = concatBytes(u8, 0x80); // [128] 
+8
source share

Paul's answer allows you to combine one TypedArray with an existing TypedArray. In ES6, you can use the following function to concatenate multiple TypedArrays:

 function concatenate(resultConstructor, ...arrays) { let totalLength = 0; for (const arr of arrays) { totalLength += arr.length; } const result = new resultConstructor(totalLength); let offset = 0; for (const arr of arrays) { result.set(arr, offset); offset += arr.length; } return result; } const ta = concatenate(Uint8Array, Uint8Array.of(1, 2), Uint8Array.of(3, 4)); console.log(ta); // Uint8Array [1, 2, 3, 4] console.log(ta.buffer.byteLength); // 4 

To add a new byte:

 const byte = 3; concatenate(Uint8Array, Uint8Array.of(1, 2), Uint8Array.of(byte)); 

This method is in ExploringJS .

+1
source share

All Articles