操作位元組陣列
在 Github 上編輯
當處理較低層級的資料時,我們經常會遇到 Uint8Arrays 形式的位元組陣列。標準函式庫中包含了一些常見的操作和查詢。
讓我們初始化一些位元組陣列
const a = new Uint8Array([0, 1, 2, 3, 4]);
const b = new Uint8Array([5, 6, 7, 8, 9]);
const c = new Uint8Array([4, 5]);
我們可以使用 concat 方法串連兩個位元組陣列
import { concat } from "jsr:@std/bytes/concat";
const d = concat([a, b]);
console.log(d); // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
有時我們需要重複某些位元組
import { repeat } from "jsr:@std/bytes/repeat";
console.log(repeat(c, 4)); // [4, 5, 4, 5, 4, 5, 4, 5]
有時我們需要變更 Uint8Array,並需要一個副本。
import { copy } from "jsr:@std/bytes/copy";
const cpy = new Uint8Array(5);
console.log("Bytes copied:", copy(b, cpy)); // 5
console.log("Bytes:", cpy); // [5, 6, 7, 8, 9]
使用 Deno CLI 在本機執行此範例
deno run https://deno-docs.dev.org.tw/examples/scripts/byte_manipulation.ts