Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

js arraybuffer转string

作者:视同仁寤戬   发布日期:2026-03-29   浏览:104

// 将 ArrayBuffer 转换为字符串的示例代码

// 创建一个函数来将 ArrayBuffer 转换为字符串
function arrayBufferToString(buffer) {
    // 创建一个 Uint8Array 视图,用于访问缓冲区中的字节
    const uint8Array = new Uint8Array(buffer);

    // 使用文本解码器将字节数组转换为字符串
    const decoder = new TextDecoder();
    return decoder.decode(uint8Array);
}

// 示例用法
const buffer = new ArrayBuffer(5); // 创建一个 5 字节的 ArrayBuffer
const uint8Array = new Uint8Array(buffer);
uint8Array[0] = 72; // H
uint8Array[1] = 101; // e
uint8Array[2] = 108; // l
uint8Array[3] = 108; // l
uint8Array[4] = 111; // o

const str = arrayBufferToString(buffer);
console.log(str); // 输出: Hello

解释说明:

  1. 创建函数 arrayBufferToString:该函数接收一个 ArrayBuffer 作为参数,并将其转换为字符串。
  2. Uint8Array 视图:我们使用 Uint8Array 来访问 ArrayBuffer 中的字节数据。
  3. TextDecoderTextDecoder 是一个内置对象,它可以将字节数组(如 Uint8Array)解码为字符串。我们使用它将 Uint8Array 转换为字符串。
  4. 示例用法:我们创建了一个包含 5 个字节的 ArrayBuffer,并手动设置了这些字节的值以表示字符串 "Hello"。然后调用 arrayBufferToString 函数将其转换为字符串并输出。

上一篇:js blob转arraybuffer

下一篇:js array reduce

大家都在看

js 数组打乱顺序

js 两个数组取交集

js 数组对象排序

js 对象数组排序

js 数组删掉第一个值

js fill

js 数组连接

js json数组

js 数组复制

js 复制数组

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站