What is ArrayBuffer equivalent to readUInt32BE node's method?

Viewed 13

readUInt32BE method reads an unsigned, big-endian 32-bit integer from buf at the specified offset.

import { Buffer } from 'node:buffer';

const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]);

console.log(buf.readUInt32BE(0).toString(16));
// Prints: 12345678

https://nodejs.org/api/buffer.html#bufreaduint32beoffset

Please, help to get the same value with ArrayBuffer without node.js.

1 Answers

When working with an ArrayBuffer of a typed array, you'd create a DataView on it to use the getUint32 method:

const buffer = Uint8Array.from([0x12, 0x34, 0x56, 0x78]).buffer;
const LE = true, BE = false;

console.log(new DataView(buffer).getUint32(0, BE).toString(16)); // 12345678

Using a Uint32Array as a view is potentially faster (in bulk), but does not guarantee a specific endianness.

Related