Typescript - decode ArrayBuffer

Viewed 471

I connected a pulse oximeter via bluetooth. Following angular-web-bluetooth https://github.com/manekinekko/angular-web-bluetooth I call the value () method. I have this answer:

DataView(7)
buffer: ArrayBuffer(7)
byteLength: 7
[[Prototype]]: ArrayBuffer
[[Int8Array]]: Int8Array(7)
0: 86
1: 84
2: 77
3: 32
4: 50
5: 48
6: 70
buffer: 
ArrayBuffer(7)
byteLength: 7
byteOffset: 0
length: 7
Symbol(Symbol.toStringTag): (…)
[[Prototype]]: TypedArray
[[Uint8Array]]: Uint8Array(7)
0: 86
1: 84
2: 77
3: 32
4: 50
5: 48
6: 70
buffer: 
ArrayBuffer(7)
byteLength: 7
byteOffset: 0
length: 7
Symbol(Symbol.toStringTag): (…)
[[Prototype]]: TypedArray
[[ArrayBufferByteLength]]: 7
[[ArrayBufferData]]: 144
byteLength: 7
byteOffset: 0

How can I decode the ArrayBuffer into a readable format of the values?

1 Answers

Your DataView's underlying ArrayBuffer values can be read with TypedArrays:

new Uint8Array(dataView.buffer).toString()

ArrayBuffers can not be read from or written to directly. A "view" interface is used for that, such as typed array views or a DataView.

const buffer = new ArrayBuffer(5)
const decoder = new TextDecoder()

// Set byte array (8 bits per item) with ASCII number code of character
const bytes = new Uint8Array(buffer)
Array.from('hello').forEach((c, i) => bytes[i] = c.charCodeAt(0))
console.log(bytes.toString(), decoder.decode(buffer))

// Use DataView to set new values
const view = new DataView(buffer)
Array.from('apple').forEach((c, i) => view.setUint8(i, c.charCodeAt(0)))
console.log(bytes.toString(), decoder.decode(buffer))

Related