39 lines
885 B
TypeScript
39 lines
885 B
TypeScript
/**
|
|
* Uint8Array 转 Base64
|
|
*/
|
|
export function uint8ArrayToBase64(bytes: Uint8Array): string {
|
|
let binary = '';
|
|
for (let i = 0; i < bytes.length; i++) {
|
|
binary += String.fromCharCode(bytes[i]);
|
|
}
|
|
return btoa(binary);
|
|
}
|
|
|
|
/**
|
|
* Base64 转 Uint8Array
|
|
*/
|
|
export function base64ToUint8Array(base64: string): Uint8Array {
|
|
const binary = atob(base64);
|
|
const bytes = new Uint8Array(binary.length);
|
|
for (let i = 0; i < binary.length; i++) {
|
|
bytes[i] = binary.charCodeAt(i);
|
|
}
|
|
return bytes;
|
|
}
|
|
|
|
/**
|
|
* 字符串转 Uint8Array
|
|
*/
|
|
export function stringToUint8Array(str: string): Uint8Array {
|
|
const encoder = new TextEncoder();
|
|
return encoder.encode(str);
|
|
}
|
|
|
|
/**
|
|
* Uint8Array 转字符串
|
|
*/
|
|
export function uint8ArrayToString(bytes: Uint8Array): string {
|
|
const decoder = new TextDecoder();
|
|
return decoder.decode(bytes);
|
|
}
|