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

convert bas64 string to array in nodejs

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

const b64 = Buffer.from(new Uint16Array([10, 100, 300])).toString('base64');
const arr = Array.from(atob(b64), c => c.charCodeAt(0)) // [10, 100, 44]

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

const b64 = Buffer.from(new Uint16Array([10, 100, 300]).join(',')).toString('base64');
const arr = new Uint16Array(Buffer.from(b64, 'base64').toString().split(','))

您遇到数据丢失。

这里一步一步地发生了什么:

// 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 ]
// }