TypedArr (TC01)
1: // Creating Typed Arrays: From an ArrayBuffer:
2:
3: import {binaryString} from "./TA%2300.js"
4:
5: const buffer = new ArrayBuffer(16); // 16 bytes
6: const int32View = new Int32Array(buffer); // View as 32-bit integers (4 elements, each 4 bytes, as buffer is 16 byte long)
7: console.log(int32View);
8: const uint8View = new Uint8Array(buffer); // View as 8-bit integers (16 elements)
9: console.log(uint8View);
10:
11: int32View[0] = 12345; // The value 12345 is a 32-bit integer. In binary, it is: 00000000 00000000 00110000 00111001
12: console.log(uint8View); // The Uint8Array reflects the change made through the Int32Array
13: console.log(binaryString(uint8View)); // In little-endian format, the bytes are stored in reverse order: 00111001 00110000 00000000 00000000
14:
15: int32View[1] = 54321;
16: int32View[2] = 12345;
17: int32View[3] = 54321;
18: console.log(uint8View); // The Uint8Array reflects the change made through the Int32Array
19: console.log(binaryString(uint8View)); // In little-endian format, the bytes are stored in reverse order: 00111001 00110000 00000000 00000000
Typed Arrays provide a way to interact with binary data in JavaScript. They offer views into an underlying ArrayBuffer, allowing you to interpret the data as different numeric types (integers, floats, etc.). Here are some common types:
• Int8Array: Signed 8-bit integers.
• Uint8Array: Unsigned 8-bit integers (0-255). Often used for representing bytes.
• Uint8ClampedArray: Unsigned 8-bit integers (0-255), with values clamped to this range. Useful for image data.
• Int16Array: Signed 16-bit integers.
• Uint16Array: Unsigned 16-bit integers.
• Int32Array: Signed 32-bit integers.
• Uint32Array: Unsigned 32-bit integers.
• Float32Array: 32-bit floating-point numbers.
• Float64Array: 64-bit floating-point numbers.
• BigInt64Array: 64-bit big integers.
• BigUint64Array: 64-bit unsigned big integers.
Int32Array(4) [ 0, 0, 0, 0 ]
Uint8Array(16) [
0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0,
0, 0, 0, 0
]
Uint8Array(16) [
57, 48, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0,
0, 0, 0, 0
]
00111001 00110000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
Uint8Array(16) [
57, 48, 0, 0, 49, 212,
0, 0, 57, 48, 0, 0,
49, 212, 0, 0
]
00111001 00110000 00000000 00000000 00110001 11010100 00000000 00000000 00111001 00110000 00000000 00000000 00110001 11010100 00000000 00000000
TypedArr context:
ES6 context:
Binary context:
Comments (
)
)
Link to this page:
http://www.vb-net.com/JavascriptES6/TC01.htm
|
|