← Math
Math

Signed numbers, overflow, and fixed-width values

Why does the app stop keeping samples after 18 hours?

Interpret fixed-width bits before comparing the values they represent.

Outcome

Calculate a fixed-width range and its signed reading, order wrapped counters within the half-range bound, and say when an independent clock is required.

Terminology (6)Terms used in this lesson

Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.

Fixed width
A value stored in a set number of bits. 16 bits hold 65,536 distinct patterns.
Two’s complement
The usual signed layout: the top bit carries weight −2¹⁵ in 16 bits, so patterns 32,768–65,535 read as −32,768 to −1.
Wrap
Arithmetic that leaves the range and continues from the other end, so a 16-bit counter goes 65,535 → 0.
Overflow
A result outside its type’s range. Wrapping, checking and failing, or undefined behavior depend on the language, type and operation; overflow does not always mean wrap.
Modular difference
b − a reduced modulo 65,536: the ticks forward from a to b around the counter.
Half-range bound
A signed modular difference orders two values correctly only if the absolute true separation is under half the range, here 32,768 ticks.

Why this matters

Sequence numbers, timers, TCP offsets and sensor counters are fixed-width, so they wrap. Comparing them as plain numbers works until the first wrap, then drops or reorders data. The fix is modular arithmetic read as signed, but it has a limit, and past that limit the counter cannot tell you what happened without another source of time.

This lesson assumes integer types and two’s complement storage from Fundamentals. How the counter travels from the watch is outside it; its values are supplied.

What a fixed-width value represents

A fixed-width word has a set number of bits, so it has only a finite set of patterns. Signed and unsigned interpretations assign different values to those same patterns. In two’s complement, the top bit carries a negative weight; choosing an interpretation is part of decoding the field.

A wrapping counter reuses its patterns as it advances. Its stored value therefore identifies a position in a cycle, rather than an unlimited elapsed count. Ordering samples needs a bound on their separation; measuring a longer gap needs additional evidence. The native examples distinguish this model from each language’s actual subtraction and conversion rules.

01Define the range

Count the patterns before reading them

A watch takes one heart-rate sample per second and stamps it with a 16-bit counter. After about 18 hours of wear the phone app stops keeping samples: the counter wrapped from 65,535 to 0, and the app still asks whether the new number is bigger.

A 16-bit counter that ticks once per second
QuantityValue
Distinct patterns2¹⁶ = 65,536
Unsigned range0 – 65,535
Signed (two’s complement) range−32,768 – 32,767
Time until the counter repeats65,536 s ≈ 18.2 h
Half the range32,768 s ≈ 9.1 h

02Read the word as signed

Read the same bits as a signed value

The watch sends a signed temperature offset as the 16-bit word 0xFFFF. What value is it?

03Order with a signed difference

Order samples with a signed modular difference

For the live importer, the stream guarantees that the compared samples were taken at most 60 seconds apart. One sample is stamped 65,530 and the arriving sample is stamped 5. Predict what each language computes for seq - last, then for the difference read as a signed 16-bit value.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
const last = 65530; // 16-bit counter values
const seq = 5;

console.log(seq - last);
console.log(((seq - last) << 16) >> 16); // low 16 bits, read as signed
What does the first line print?

Every version’s second line is 11. Given the live stream’s age bound, the arriving sample is 11 ticks newer. Read the modular difference as signed, and positive means newer, negative means older, zero means the same sample. This watch takes one sample per tick; without the age bound, equal counter values could instead be a full wrap apart. At exactly −32,768 both ways around are half the range, so the order is ambiguous.

04Convert the bound to time

The bound is a time limit

With one tick per second, what is the longest gap between samples that the signed difference orders correctly?

A watch left on a charger overnight, away from the phone, easily exceeds nine hours. Then the counter alone gives a wrong order, and no arithmetic on it can recover the gap.

05Bring in the clock

Bring in an independent clock

The watch also reports wall-clock time with some tolerance. The counter moved from 60,000 to 2,000, so the forward ticks modulo 65,536 are 7,536. The true gap is one of 7,536, 73,072, 138,608 and so on. The clock says 72,000 s ± 1,500 s.

How many seconds passed?

06Sync the samples

Build the sample importer

The importer first needs to decode a signed watch field, including its negative boundary. Its live stream then needs to reject repeats and stale samples across a counter wrap. Reconnecting after days away breaks the live age guarantee: combine the modular counter with an independently measured clock window, and report when that window cannot select one gap.

In the frontend Bluetooth packets in Next.js and Svelte Optional

A Web Bluetooth notification arrives as a DataView. Read a documented little-endian counter with getUint16(0, true); the arithmetic then uses ordinary numbers, so ((seq - last) << 16) >> 16 reinterprets the low 16 bits as signed. Drop a packet whose difference is zero or negative. That rule is safe only when the true separation of the compared samples is known to be less than 32,768 ticks. Frequent notifications alone do not establish that bound: a delayed old packet can still arrive. The connection owner resets the excerpt’s state when that guarantee is lost; an offline import needs the clock-based calculation instead.

Estimate.tsx
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
'use client';

import { useRef, useState } from 'react';

// Requires compared samples to be known less than 32,768 ticks apart.
// Reset the stream state when this guarantee is lost.
const ticksSince = (last: number, seq: number) => ((seq - last) << 16) >> 16;

export function useHeartRate() {
  const last = useRef<number | null>(null);
  const [beats, setBeats] = useState<number[]>([]);

  function resetStream() {
    last.current = null;
  }

  function onPacket(view: DataView) {
    const seq = view.getUint16(0, true); // little-endian counter
    const bpm = view.getUint8(2);

    if (last.current !== null && ticksSince(last.current, seq) <= 0) return; // repeat or stale

    last.current = seq;
    setBeats((list) => [...list, bpm]);
  }

  return { beats, onPacket, resetStream };
}

Check this idea later
An 8-bit sequence counter reads 250 and then 3. What is the forward distance modulo 256?
A 16-bit counter ticks every 10 ms. What is the longest gap a signed difference can order?
Sources

The watch and its counter are a worked model. Subtraction behavior was run on Node 22, Go 1.27, rustc 1.99 and clang 17.

Report a problem in this lesson

For typos, mistakes and things that don’t work. We read every report and fix what’s wrong, but we don’t reply here, so a question won’t get an answer.