ArrayBuffer: ArrayBuffer object is used to represent a generic raw binary data buffer. You can think of as contiguous memory buffer of the fixed length. You can refer it as a “byte array”, but you can’t directly modify it, instead you have to create view on top it using typed arrays like Uint8Array, Int16Array, Uint32Array,… etc.
// You can run below code inside node REPL
// create an array buffer of 8 bytes
const buffer = new ArrayBuffer(8)
// buffer
// ArrayBuffer {
// [Uint8Contents]: <00 00 00 00 00 00 00 00>,
// byteLength: 8
// }
const ua8 = new Uint8Array(buffer)
const a8 = new Int8Array(buffer)
const a16 = new Int16Array(buffer)
ua8[0] = 255
ua8[1] = 255
console.log(a16[0])
// above will print `-1`. You can brainstorm it. Hint: Two's Complement and the bytes we are changing.There is nothing new here, you can create this same buffers in any other language like for example in c you can use malloc
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
void print_raw_buffer(void *buffer, size_t size);
int main()
{
void *buffer = malloc(8);
uint8_t *ua8 = buffer;
const int8_t *a8 = buffer;
const int16_t *a16 = buffer;
ua8[0] = 255;
ua8[1] = 255;
print_raw_buffer(buffer, sizeof(buffer)); // ff ff 00 00 00 00 00 00
printf("%d\n", a16[0]); // -1
free(buffer);
return 0;
}
void print_raw_buffer(void *buffer, size_t size)
{
uint8_t *u8 = buffer;
for (size_t i = 0; i < size; i++)
{
printf("%02x ", u8[i]);
}
printf("\n");
}