From 7c3701364542355c29b2e4ebc6d719ddd123c0f2 Mon Sep 17 00:00:00 2001 From: Sebastiano Tronto Date: Thu, 24 Jul 2025 09:00:49 +0200 Subject: Use bit trick for portable and arm popcount --- test/016_popcount_u32/00_all.in | 0 test/016_popcount_u32/00_all.out | 1 + test/016_popcount_u32/popcount_u32_tests.c | 43 ++++++++++++++++++++++++++++++ 3 files changed, 44 insertions(+) create mode 100644 test/016_popcount_u32/00_all.in create mode 100644 test/016_popcount_u32/00_all.out create mode 100644 test/016_popcount_u32/popcount_u32_tests.c (limited to 'test') diff --git a/test/016_popcount_u32/00_all.in b/test/016_popcount_u32/00_all.in new file mode 100644 index 0000000..e69de29 diff --git a/test/016_popcount_u32/00_all.out b/test/016_popcount_u32/00_all.out new file mode 100644 index 0000000..7326d96 --- /dev/null +++ b/test/016_popcount_u32/00_all.out @@ -0,0 +1 @@ +Ok diff --git a/test/016_popcount_u32/popcount_u32_tests.c b/test/016_popcount_u32/popcount_u32_tests.c new file mode 100644 index 0000000..ff60c68 --- /dev/null +++ b/test/016_popcount_u32/popcount_u32_tests.c @@ -0,0 +1,43 @@ +#include "../test.h" + +int popcount_u32(uint32_t x); + +int +popcount_u32_simple(uint32_t x) +{ + int ret; + + for (ret = 0; x != 0; x >>= 1) + ret += x & 1; + + return ret; +} + +bool +correct(uint32_t x) +{ + int expected = popcount_u32_simple(x); + int actual = popcount_u32(x); + if (actual != expected) { + printf("Error at %" PRIu32 ": expected %d bits, found %d\n", + x, expected, actual); + return false; + } + return true; +} + +void run(void) { + uint32_t i; + + /* Test all numbers up to 2^16, and other ranges of 2^16 numbers */ + for (i = 0; i < 0xFFFF; i++) { + if (!correct(i) || + !correct(i + UINT32_C(0xFFFF0000)) || + !correct(i + UINT32_C(1000000)) || + !correct(i + UINT32_C(1)) || + !correct(i + UINT32_C(1234567))) + return; + } + + printf("Ok\n"); +} -- cgit v1.3