在JavaScript中,可以通過不同的方式將字符串序列化為二進制數據。以下是幾種常見的方法:
-
TextEncoder 和 TextDecoder
JavaScript 提供了TextEncoder
和TextDecoder
對象,可以用來處理字符串和二進制數據之間的轉換。// 將字符串轉換為二進制數據 const encoder = new TextEncoder(); const text = 'Hello, 你好!'; const encoded = encoder.encode(text);// 將二進制數據解碼為字符串 const decoder = new TextDecoder(); const decoded = decoder.decode(encoded);console.log(encoded); // Uint8Array(15) [72, 101, 108, 108, 111, 44, 32, 228, 189, 160, 229, 165, 189, 33] console.log(decoded); // Hello, 你好!
這種方法可以處理 UTF-8 編碼的字符串。
-
TypedArray
可以使用 TypedArray 來處理二進制數據,例如Uint8Array
。// 將字符串轉換為 Uint8Array const text = 'Hello, 你好!'; const bytes = new Uint8Array(text.length); for (let i = 0; i < text.length; i++) {bytes[i] = text.charCodeAt(i); }console.log(bytes); // Uint8Array(15) [72, 101, 108, 108, 111, 44, 32, 203, 156, 229, 165, 189, 33]
這種方法需要注意字符編碼的處理,特別是非 ASCII 字符。
-
直接操作字符串的 UTF-16 編碼
JavaScript 中的字符串使用 UTF-16 編碼,可以直接操作其編碼單元(16 位)。// 將字符串轉換為 UTF-16 編碼 const text = 'Hello, 你好!'; const bytes = new Uint16Array(text.length); for (let i = 0; i < text.length; i++) {bytes[i] = text.charCodeAt(i); }console.log(bytes); // Uint16Array(8) [72, 101, 108, 108, 111, 44, 20320, 22909]
這種方法比較底層,需要理解字符串的 UTF-16 編碼方式。
根據具體的需求和場景,可以選擇適合的方法將字符串序列化為二進制數據。