【问题标题】:convert bas64 string to array in nodejs在nodejs中将bas64字符串转换为数组
【发布时间】:2020-11-04 19:11:17
【问题描述】:

我有从 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]

【问题讨论】:

    标签: javascript node.js base64 arraybuffer typed-arrays


    【解决方案1】:

    您正在经历数据丢失。

    这里是正在发生的事情的一步一步:

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

    【讨论】:

    • 它适用于 Uint16Array [10, 100, 300],但不适用于 [10, 100, 60000]。这给出了 [10, 100, 50016]。这很奇怪,因为 16 位值的范围从 0 到 65535
    • thks,我编辑答案让它工作。我删除了 atob 依赖项,因为转换似乎有问题
    • 很好,它有效。谢谢。 User863 的解决方案同样有效,但您的解决方案似乎更快。
    【解决方案2】:

    尝试使用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(','))
    

    【讨论】:

      猜你喜欢
      • 2020-08-23
      • 1970-01-01
      • 1970-01-01
      • 2020-08-13
      • 2015-11-11
      • 2017-11-27
      • 2021-05-09
      • 2023-03-19
      相关资源
      最近更新 更多