← All problems · Protocols & Parsing
Validate an Additive Packet Checksum
A valid nonempty packet including its checksum sums to zero modulo 256. Return 1 for valid packets.
Implement int valid_sum(const uint8_t *p, size_t n).
Choose C or C++ and write your code on the right and press Run (or Ctrl + Enter). Hidden tests check your functions and print the result below the editor.
Accumulate modulo 256.
#include <stdio.h>
#include <stdint.h>
#include <stddef.h>
#include <string.h>
int valid_sum(const uint8_t *p, size_t n)
{
if(!n)return 0; uint8_t s=0; for(size_t i=0;i<n;++i)s=(uint8_t)(s+p[i]); return s==0;
}
#include <cstdio>
#include <cstdint>
#include <cstddef>
#include <cstring>
int valid_sum(const std::uint8_t *p, std::size_t n)
{
if(!n)return 0; std::uint8_t s=0; for(std::size_t i=0;i<n;++i)s=(std::uint8_t)(s+p[i]); return s==0;
}
An eight-bit accumulator naturally retains the low byte of the sum.
solution.c
OutputPress Run to compile and test your code.
Show the hidden tests
/* ---- tests ---- */
static int fails;
#define CHECK(c) do { if (!(c)) { printf("FAIL line %d: %s\n", __LINE__, #c); fails++; } } while (0)
int main(void)
{
uint8_t a[]={10,20,226};
CHECK(valid_sum(a,3)==1);
CHECK(valid_sum(a,2)==0);
CHECK(valid_sum(a,0)==0);
puts(fails ? "Some tests failed" : "All tests passed");
return fails != 0;
}