我有一个从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]
发布于 2020-07-15 19:00:37
您正在经历数据丢失。
下面是正在发生的事情的一步一步:
// 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 ]
// }
发布于 2020-07-15 18:14:59
尝试使用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(','))
https://stackoverflow.com/questions/62912288
复制相似问题