skip to content

A browser page's JavaScript parses PNG and WAV headers with `new Uint32Array(buffer, offset, 1)`: the PNG width reads 537067520 for an 800-pixel image and a later PNG field throws RangeError; why, and how should it read them?

level: seniorimportance: should knowfreq 24%

answer

  1. dump the raw bytes first
  2. platform order versus format order
  3. alignment of byteOffset
  4. why WAV looked correct
  5. one DataView, a flag per call

basics

~20 s

Uint32Array reads in platform byte order and requires offsets that are multiples of 4, while PNG is big-endian with some fields at odd offsets. Use DataView instead: getUint32 accepts any offset, and each call states the format's byte order.

solid answer

~40 s

Both failures come from using a typed array, a view meant for arrays of native numbers, to read a file format. A `Uint32Array` uses the platform's byte order, so on a little-endian host the PNG width bytes `00 00 03 20` read as `0x20030000`, which is 537067520. The WAV sample rate looks right on that host only because WAV is little-endian too, which hides the bug. The `RangeError` comes from alignment: `byteOffset` must be a multiple of 4, and PNG's second chunk starts at byte 33. The fix is one `DataView` over the buffer, with the format's byte order in every call: `view.getUint32(16)` for PNG, `view.getUint32(24, true)` for WAV. `DataView` accepts any offset and throws `RangeError` on a truncated file. Check the signature first, and validate each declared length against `byteLength` before trusting it.

code

javascript · 17 lines
javascript
function readPngSize(buffer) {
  const view = new DataView(buffer);
  const signature = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];
  if (buffer.byteLength < 24 || signature.some((b, i) => view.getUint8(i) !== b)) {
    throw new Error("not a PNG");
  }
  return { width: view.getUint32(16), height: view.getUint32(20) };
}

const bytes = new Uint8Array(24);
bytes.set([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
bytes.set([0x00, 0x00, 0x03, 0x20, 0x00, 0x00, 0x02, 0x58], 16);

const { width, height } = readPngSize(bytes.buffer);
console.log(width, height); // 800 600
// on a little-endian host, the mistaken read:
console.log(new Uint32Array(bytes.buffer, 16, 1)[0]); // 537067520

go deeper

for a junior

Recall that a file format defines its own byte order, and that a typed array ignores it. Know that DataView is the tool for reading a value at a given offset.

for a middle

Explain the two separate causes here: platform byte order for the wrong width, and the byteOffset multiple rule for the RangeError. Work the width out by hand from the four bytes.

for a senior

Show the diagnosis as well as the fix: dump bytes, test both orders, and explain why the WAV path was a false reassurance. Then harden the parser with signature checks and validated declared lengths.

for a principal

The tradeoff angle is where parsing code lives. One audited reader per format, with fixtures that exercise both byte orders and malformed files, costs little and stops untrusted bytes spreading through the code unchecked.

## Diagnosing the width A wildly wrong integer from a file that opens fine elsewhere usually means the offset or the byte order is wrong. Do not guess between them. Work through it in order: 1. Dump the raw bytes at that offset with a `Uint8Array`, since a single-byte view cannot be affected by byte order. 2. Read them by hand in each order. Here the bytes are `00 00 03 20`. 3. Compare with the value you expected. Big-endian gives `0x00000320`, which is 800, and little-endian gives `0x20030000`, which is 537067520. The expected number appearing under one order means the offset is right and the order is wrong. PNG stores its multi-byte integers **big-endian**, and a typed array reads in the **platform's** order, which on most machines is little-endian. So this is not a corrupt file and not a bad offset; the view can't read this format's order on this host. ## Why the WAV header looked correct WAV is a RIFF format, and its integers are **little-endian**. On a little-endian host, `new Uint32Array(buffer, 24, 1)[0]` happens to return the right sample rate, 44100, so a test suite built around WAV files passes. That is a false signal: the code never expressed the format's byte order at all, and it only agrees with WAV because the host does. It would read WAV wrongly and PNG correctly on a big-endian host. ## Why the RangeError appears A typed array view requires its `byteOffset` to be a multiple of `BYTES_PER_ELEMENT`, which is 4 for `Uint32Array`. The first PNG fields happen to be aligned, but file formats are packed with no regard for it. After the 8-byte signature, the first chunk has a 4-byte length, a 4-byte type, 13 bytes of data and a 4-byte checksum, so the next chunk's length field sits at byte 33. `new Uint32Array(buffer, 33, 1)` throws `RangeError`, and no wider element type helps with values packed at arbitrary positions. ## What the parser should do One `DataView` over the whole buffer solves both problems, because it has no alignment rule and takes the byte order on each access: ```js function readPngSize(buffer) { const view = new DataView(buffer); const signature = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]; if (buffer.byteLength < 24 || signature.some((b, i) => view.getUint8(i) !== b)) { throw new Error("not a PNG"); } return { width: view.getUint32(16), height: view.getUint32(20) }; } ``` | Concern | `new Uint32Array(buffer, offset, 1)` | `DataView` | |---|---|---| | Byte order | the platform's, fixed | chosen per call | | Offset | multiple of 4 | any byte | | Mixed field widths | a new view per width | one view, many accessors | | Past the end | `RangeError` at construction | `RangeError` on the read | ## Hardening beyond the fix - **Pass the flag on every multi-byte call.** Forget `true` on `view.getUint16(22)` and a stereo file reports 512 channels; forget it on `view.getUint16(34)` and 16-bit audio reports 4096 bits, all while the sample rate stays right. One wrong field among correct ones points at a single missing flag. - **Keep byte order in one place.** A small reader for each format, with its order set once inside it, means no call site can forget. - **Check the signature before trusting any offset.** A wrong file otherwise produces numbers that look valid. - **Treat declared lengths as untrusted input.** A chunk length comes from the file, so compare it against `byteLength` before you use it for an offset or an allocation. - **Do not assume a fixed layout where the format has none.** The offsets 22, 24 and 34 hold for the common WAV layout, where `fmt ` comes first, but other chunks are allowed before it, so a robust reader walks the chunks. - **Read only what you need.** For a header in a large upload, `await file.slice(0, 64).arrayBuffer()` avoids loading the whole file. Typed arrays do still have a place in a binary format. A `Uint8Array` is the right view for raw bytes such as a signature. A wider typed array over a long run of samples is only safe once the format's order matches the host and the offset is aligned, so a careful parser checks both or falls back to a `DataView` loop.

  • A WAV parser using `DataView` gets the sample rate right but reports 512 channels. What is the bug?
    The `littleEndian` argument is missing on that one call. Two channels are stored as the bytes `02 00`, and `getUint16(22)` reads them big-endian as `0x0200`, which is 512. The sample-rate call passed `true`, so it was right. The flag belongs to each call, which is why one field can be wrong alone.
  • How would you read a four-character chunk tag such as `RIFF` from the buffer?
    As bytes, with `getUint8` or a `Uint8Array`, because a tag is a byte sequence with no byte order. If you compare it as one integer, read it big-endian whatever the format's own order is: `view.getUint32(0)` over `RIFF` gives `0x52494646`, so the digits appear in the order of the characters.
  • Why doesn't passing your own tests on a laptop prove the parser is portable?
    Most machines are little-endian, so a typed array read of little-endian data gives right answers on every machine you are likely to test on. The reliance on native order is invisible until the host differs. A `DataView` with the format's order states the assumption in code, so the result no longer depends on the host.

  • A Uint32Array is fine for any 32-bit file field, since the width matches.
  • A width of 537067520 for a valid image means the file is corrupt.
  • DataView also requires offsets aligned to the size of the value being read.
  • Code that reads WAV correctly has proved that it handles byte order.
  • PNG integers are little-endian, because most machines reading them are.
  • Reading past the end of a DataView returns undefined, like a typed array index.