首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在nodejs中将bas64字符串转换为数组

在nodejs中将bas64字符串转换为数组
EN

Stack Overflow用户
提问于 2020-07-15 17:57:03
回答 2查看 116关注 0票数 0

我有一个从uint16Array编码的base64字符串。我想把它转换成一个数组,但是转换后的值是8位的,而我需要它们是16位的。

代码语言:javascript
运行
复制
const b64 = Buffer.from(new Uint16Array([10, 100, 300])).toString('base64');
const arr = Array.from(atob(b64), c => c.charCodeAt(0)) // [10, 100, 44]
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-07-15 19:00:37

您正在经历数据丢失。

下面是正在发生的事情的一步一步:

代码语言:javascript
运行
复制
// in memory you have store 16bit per each char
const source = new Uint16Array([
  10, ///  0000 0000 0000 1010
  100, //  0000 0000 0110 0100
  300, //  0000 0001 0010 1100
  60000 // 1110 1010 0110 0000
])

// there is not information loss here, we use the raw buffer (array of bytes)
const b64 = Buffer.from(source.buffer).toString('base64')

// get the raw buffer
const buf = Buffer.from(b64, 'base64')

// create the Uint 16, reading 2 byte per char
const destination = new Uint16Array(buf.buffer, buf.byteOffset, buf.length / Uint16Array.BYTES_PER_ELEMENT)

console.log({
  source,
  b64,
  backBuffer,
  destination
})

// {
//   source: Uint16Array [ 10, 100, 300, 60000 ],
//   b64: 'CgBkACwBYOo=',
//   destination: Uint16Array [ 10, 100, 300, 60000 ]
// }
票数 3
EN

Stack Overflow用户

发布于 2020-07-15 18:14:59

尝试使用Buffer.from(b64, 'base64').toString()进行解码

代码语言:javascript
运行
复制
const b64 = Buffer.from(new Uint16Array([10, 100, 300]).join(',')).toString('base64');
const arr = new Uint16Array(Buffer.from(b64, 'base64').toString().split(','))
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62912288

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档