0

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]

2 Answers 2

4

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 ]
// }
Sign up to request clarification or add additional context in comments.

3 Comments

It works fine with Uint16Array [10, 100, 300] but it does not work for, says, [10, 100, 60000]. which gives [10, 100, 50016]. it is weird as 16 bits values range from 0 to 65535
thks, i edit the answer to let it work. I remove the atob dependency since seems to have problems with the conversion
great, it works. thanks. User863's solution worked as well but yours seems to be faster.
3

Try using Buffer.from(b64, 'base64').toString() to decode

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.