ArrayBuffer, Binary Arrays

ArrayBuffer, Binary Arrays

ArrayBuffer & Binary Arrays in JavaScript

What is ArrayBuffer?

ArrayBuffer is a low-level binary data structure that allows you to store raw binary data in memory. It is useful when dealing with WebSockets, File APIs, or binary data processing (e.g., images, audio, and video).

1. Understanding ArrayBuffer

An ArrayBuffer represents a fixed-length chunk of memory that can be viewed and manipulated using typed arrays like Uint8Array, Float32Array, etc.

Creating an ArrayBuffer

let buffer = new ArrayBuffer(8); // 8 bytes (64 bits) console.log(buffer.byteLength); // 8

🔹 Doesn't store data directly—you need a view (TypedArray) to manipulate it.

2. Working with Typed Arrays (Uint8Array, Float32Array, etc.)

Typed arrays allow you to interpret an ArrayBuffer as a specific data type.

Writing Data to an ArrayBuffer

let buffer = new ArrayBuffer(8); // 8 bytes let view = new Uint8Array(buffer); // 8-bit unsigned integer view view[0] = 10; view[1] = 255; // Max value for Uint8Array view[2] = 300; // Will be truncated to 44 (300 % 256) console.log(view); // Uint8Array(8) [10, 255, 44, 0, 0, 0, 0, 0]

🔹 Uint8Array stores each element in 1 byte (0-255).
🔹 300 is truncated because Uint8Array supports only 0 to 255 (300 % 256 = 44).

3. Typed Array Variants

TypedArraySize per elementRange
Int8Array1 byte-128 to 127
Uint8Array1 byte0 to 255
Uint8ClampedArray1 byte0 to 255 (values > 255 are set to 255)
Int16Array2 bytes-32,768 to 32,767
Uint16Array2 bytes0 to 65,535
Int32Array4 bytes-2,147,483,648 to 2,147,483,647
Uint32Array4 bytes0 to 4,294,967,295
Float32Array4 bytesFloating-point numbers
Float64Array8 bytesHigh-precision floating points

Example: Using a Float32Array

let floatBuffer = new ArrayBuffer(16); let floatView = new Float32Array(floatBuffer); floatView[0] = 3.14; floatView[1] = 2.71; console.log(floatView); // Float32Array(4) [3.14, 2.71, 0, 0]

🔹 Float32Array stores 32-bit floating-point numbers.

4. Reading Binary Data with DataView

DataView allows more precise control over binary data, letting you read/write different types at different offsets.

Example: Using DataView

let buffer = new ArrayBuffer(8); let view = new DataView(buffer); // Writing values at specific byte offsets view.setInt16(0, 42); // Store 16-bit integer at byte 0 view.setFloat32(2, 3.14); // Store 32-bit float at byte 2 // Reading values from the buffer console.log(view.getInt16(0)); // 42 console.log(view.getFloat32(2)); // 3.14

🔹 setInt16(0, 42) stores 42 as a 16-bit integer at byte 0.
🔹 setFloat32(2, 3.14) stores 3.14 as a 32-bit float at byte 2.

5. Converting ArrayBuffer to String (Text Encoding)

Using TextDecoder and TextEncoder

Useful for encoding/decoding binary data into strings.

Encoding a String into an ArrayBuffer

let encoder = new TextEncoder(); let encoded = encoder.encode("Hello"); console.log(encoded); // Uint8Array(5) [72, 101, 108, 108, 111]

🔹 Converts "Hello" into its UTF-8 binary representation.

Decoding an ArrayBuffer into a String

let decoder = new TextDecoder(); console.log(decoder.decode(encoded)); // "Hello"

🔹 Converts binary data back into a string.

6. Real-World Applications of ArrayBuffer

📌 1. Handling Files (FileReader)

Read a file as an ArrayBuffer:

document.getElementById("fileInput").addEventListener("change", function(event) { let file = event.target.files[0]; let reader = new FileReader(); reader.onload = function() { let buffer = reader.result; console.log("Binary Data:", new Uint8Array(buffer)); }; reader.readAsArrayBuffer(file); });

🔹 Converts a file into binary data.

📌 2. WebSockets (Binary Data Transfer)

Send and receive binary data efficiently.

let socket = new WebSocket("wss://example.com"); socket.binaryType = "arraybuffer"; // Set WebSocket to receive binary data socket.onmessage = function(event) { let buffer = event.data; let view = new Uint8Array(buffer); console.log("Received Binary Data:", view); };

🔹 Transfers binary data over a WebSocket connection.

📌 3. Processing Images

Using Canvas to convert an image to ArrayBuffer:

let canvas = document.createElement("canvas"); let ctx = canvas.getContext("2d"); let img = new Image(); img.onload = function() { ctx.drawImage(img, 0, 0); canvas.toBlob(function(blob) { let reader = new FileReader(); reader.onload = function() { console.log("Image as ArrayBuffer:", new Uint8Array(reader.result)); }; reader.readAsArrayBuffer(blob); }); }; img.src = "image.jpg";

🔹 Converts an image into raw binary data for processing.

🔹 Summary: Why Use ArrayBuffer?

FeatureArrayBuffer
Binary Data✅ Yes
Fast Performance✅ Yes
Manipulate Memory✅ Yes
Supports Large Data✅ Yes
Used in Web APIs✅ Yes

ArrayBuffer is essential for performance-critical applications like handling binary data, WebSockets, image processing, and file manipulation.

🎯 Conclusion

ArrayBuffer stores raw binary data in memory.
Typed Arrays (Uint8Array, Float32Array, etc.) view and manipulate the buffer.
DataView allows precise control over binary data.
TextEncoder and TextDecoder help with text encoding.
Real-world use cases: File reading, WebSockets, image processing, etc.

🔹 Need help implementing ArrayBuffer? Let me know!

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close