function internetChecksum
internetChecksum(data: Uint8Array): number

Computes the 16-bit Internet checksum (RFC 1071) over a span of bytes.

The checksum is the 16-bit one's complement of the one's complement sum of all 16-bit words in the span. If the byte length is odd, the trailing byte is padded with zero for the purposes of the sum.

Callers typically zero out the checksum field of a header before computing, then write the returned value back into that field. A subsequent call over the completed packet returns 0, the standard receiver-side verification.

The function is layout-agnostic — it operates on whatever bytes are passed in. For protocols that include a pseudo-header in the checksum (UDP, TCP), the caller is responsible for assembling the pseudo-header followed by the datagram and passing the concatenation.

Examples

RFC 1071 §3 worked example

import { assertEquals } from "@std/assert";
import { internetChecksum } from "@binstruct/inet";

// deno-fmt-ignore
const sample = new Uint8Array([
  0x00, 0x01, 0xf2, 0x03, 0xf4, 0xf5, 0xf6, 0xf7,
]);
assertEquals(internetChecksum(sample), 0x220d);

Verify a checksummed packet round-trips to zero

import { assertEquals } from "@std/assert";
import { internetChecksum } from "@binstruct/inet";

// deno-fmt-ignore
const echoRequest = new Uint8Array([
  0x08, 0x00, 0xf7, 0xfd, 0x00, 0x01, 0x00, 0x01,
]);
assertEquals(internetChecksum(echoRequest), 0x0000);

Parameters

Bytes to checksum.

Return Type

number

A 16-bit unsigned integer suitable for direct assignment into a u16be field.