Problems › JavaScript › network
Single-byte checksum of a payload
Many lightweight protocols use a one-byte checksum: just the sum of all bytes modulo 256.
- Each element in the payload is a byte value (0–255).
- The checksum is the sum of all bytes modulo 256.
- An empty payload has a checksum of 0.
checksumByte(payload: list<int>) → int
Where you start
function checksumByte(payload) {
}
Worked examples
| Call | Result |
|---|---|
checksumByte([1,2,3]) | 6 |
checksumByte([255,1]) | 0 |
checksumByte([]) | 0 |
checksumByte([128,128]) | 0 |
Hint
Add every element, then take the remainder when divided by 256.
Reference solution in JavaScript
function checksumByte(payload) {
let sum = 0;
for (const b of payload) sum += b;
return sum % 256;
}