You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将逗号分隔的十六进制图像数据字符串转换为ArrayBuffer?

将逗号分隔的十六进制字符串转换为ArrayBuffer

实现步骤

  • 清洗输入字符串:移除换行符、多余空格,按, 分割得到单个十六进制值的数组
  • 转换每个十六进制值为8位整数(范围0-255)
  • 通过Uint8Array构建字节数组,再提取对应的ArrayBuffer

代码示例

// 示例输入的十六进制字符串
const hexImageData = `0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff`;

// 1. 清洗字符串并分割为单个十六进制值
const cleanedHexValues = hexImageData.replace(/\n/g, '').split(', ');

// 2. 将每个十六进制值转为8位整数
const byteNumbers = cleanedHexValues.map(hexStr => parseInt(hexStr, 16));

// 3. 构建Uint8Array并获取ArrayBuffer
const targetBuffer = new Uint8Array(byteNumbers).buffer;

// 此时targetBuffer就是所需的ArrayBuffer对象
console.log(targetBuffer);

注意点

  • 确保所有十六进制值都是有效的单字节值(0x00到0xff),超出范围的数值会导致字节溢出,破坏图像数据
  • 如果原始字符串存在不规则空白(比如多个空格),可以把split(', ')替换为split(/,\s*/)来适配更多场景

内容的提问来源于stack exchange,提问作者user2402616

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 20:09:10