jsrosetta

Collections

Uint8Array

Uint8Array của Node.js (set, subarray, fill) so với []uint8 của Go, &[u8] của Rust, [UInt8] của Swift và byte[] của Java.

Phiên bản tối thiểu
Node.js ≥ 12.20Go ≥ 1.0Rust ≥ 1.58Swift ≥ 4.0Java ≥ 25
Đã chạy thử trên
Node.js 24.12.0Go 1.27.1Rust 1.98.1Swift 6.2.4Java 25.0.4.1

Code Node.js là ES module: lưu file .mjs hoặc đặt "type": "module" trong package.json.

Uint8Array trong Node.js là một TypedArray chỉ chứa số nguyên 8-bit không dấu, có sẵn method set/subarray/fill. Go không có kiểu riêng cho việc này — bạn dùng thẳng []uint8 (giống hệt []byte, vì byte chỉ là bí danh của uint8) và các thao tác slice/loop thông thường của ngôn ngữ. Rust cũng vậy, dùng Vec<u8>/&[u8] cùng method có sẵn trên slice (copy_from_slice, fill). Swift dùng [UInt8] (value type). Java thì khác hẳn: byte luôn có dấu (-128..127), không có kiểu 8-bit không dấu, và mảng nguyên gốc (byte[]) không có "view" nhẹ như subarray/slice — Arrays.copyOfRange luôn tạo bản sao.

Khởi tạo, ghi và lấy subarray

const array = new Uint8Array(10)
console.log(array) // Uint8Array(10) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
 
const offset = 1
array.set([1, 2, 3], offset)
console.log(array) // Uint8Array(10) [0, 1, 2, 3, 0, 0, 0, 0, 0, 0]
 
const sub = array.subarray(2)
console.log(sub) // Uint8Array(8) [2, 3, 0, 0, 0, 0, 0, 0]
 
const sub2 = array.subarray(2, 4)
console.log(sub2) // Uint8Array(2) [2, 3]

Fill và độ dài (byteLength)

const value = 9
const start = 5
const end = 10
array.fill(value, start, end)
console.log(array) // Uint8Array(10) [0, 1, 2, 3, 0, 9, 9, 9, 9, 9]
 
console.log(array.byteLength) // 10

Tham khảo: github.com/miguelmota/golang-for-nodejs-developers#uint8-arrays