Search code examples
javascriptnode.jsbase64arraybuffertyped-arrays

convert bas64 string to array in nodejs


I have base64 string encoded from a uint16Array . I want to convert it to an Array but the converted values are on 8 bits whereas i need them to be on 16 bits.

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

Solution

  • You are experiencing data loss.

    Here a step by step of what is happening:

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