Uint8ClampedArray Saturates Bytes Not Wraps
Contrast Uint8ClampedArray saturating clamping to 0..255 with round-half-to-even against Uint8Array modulo-256 wraparound for pixel and signal channels.
Code
const inputs = [-25, 0.5, 1.5, 2.5, 255, 290, NaN];
const clamped = new Uint8ClampedArray(inputs);
const wrapped = new Uint8Array(inputs);
for (let i = 0; i < inputs.length; i++) {
const inputCol = String(inputs[i]).padStart(5);
const clampCol = String(clamped[i]).padStart(3);
const wrapCol = String(wrapped[i]).padStart(3);
console.log(`${inputCol} -> clamped: ${clampCol} | wrapped: ${wrapCol}`);
}
// Note: 0.5 rounds to 0, 1.5 and 2.5 round to even (2), while negatives clamp to 0
console.log('brightness +60 clamp:', new Uint8ClampedArray([220 + 60])[0]);Output
Captured from a sandboxed run of this snippet in the build pipeline.
-25 -> clamped: 0 | wrapped: 231
0.5 -> clamped: 0 | wrapped: 0
1.5 -> clamped: 2 | wrapped: 1
2.5 -> clamped: 2 | wrapped: 2
255 -> clamped: 255 | wrapped: 255
290 -> clamped: 255 | wrapped: 34
NaN -> clamped: 0 | wrapped: 0
brightness +60 clamp: 255Implementation trace — Uint8ClampedArray Saturates Bytes Not Wraps
One loop does the cycling here: for (let i = 0; i < inputs.length; i++).
Demo state sits in top-level bindings: inputs, clamped, wrapped.
What to watch for
- Nothing to vet in a supply-chain review — the file pulls in no packages.
Applying it
The run prints brightness +60 clamp: — each prefix names the step that produced it.
Statements that matter
const inputs = [-25, 0.5, 1.5, 2.5, 255, 290, NaN];
const clampCol = String(clamped[i]).padStart(3);
const inputCol = String(inputs[i]).padStart(5);
Interactive Tools for This Topic
Hex Dump ViewerPreview any text as a classic hexadecimal dump with byte offsets, sixteen bytes per row, and an ASCII column for quick inspection.Binary Text ConverterConvert UTF-8 text to 8-bit binary groups and decode binary back to text with strict validation.Bitwise Operations CalculatorCompute AND, OR, XOR, NOT, and shifts on 32-bit unsigned operands with binary, hex, and signed decimal views.Byte Size ConverterShow one byte count in every unit side by side, using decimal (kB/MB/GB) or binary (KiB/MiB/GiB) standards.
FAQ
- Can I paste this into a project as-is?
- Yes. Paste it in and run; no package manager step is needed. Its state lives in module-level bindings: `inputs`, `clamped`, `wrapped`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.