Skip to content

Instantly share code, notes, and snippets.

@aclamk
Created June 26, 2018 11:22
Show Gist options
  • Save aclamk/e6f2717db7d9934b9e14f0f18181aca2 to your computer and use it in GitHub Desktop.
Save aclamk/e6f2717db7d9934b9e14f0f18181aca2 to your computer and use it in GitHub Desktop.
Test ffsll
#include <assert.h>
#include <inttypes.h>
#include <stddef.h>
#include <stdlib.h>
#include <stdio.h>
typedef uint64_t slot_t;
static constexpr size_t bits_per_slot = sizeof(slot_t) * 8;
static inline ssize_t count_0s_gcc(slot_t slot_val, size_t start_pos)
{
size_t pos = __builtin_ffsll(slot_val >> start_pos);
if (pos == 0)
return sizeof(slot_t)*8 - start_pos;
return pos - 1;
}
static inline ssize_t count_0s_other(slot_t slot_val, size_t start_pos)
{
size_t pos = start_pos;
slot_t mask = slot_t(1) << pos;
while (pos < bits_per_slot && (slot_val & mask) == 0) {
mask <<= 1;
pos++;
}
return pos - start_pos;
}
int main(int argc, char** argv)
{
slot_t v = 0;
for (int i=0;i<100000000;i++)
{
size_t len = rand()%16 + 1;
slot_t val = slot_t(0 - rand()%2) >> (bits_per_slot - len);
v = (v << len) | val;
//printf("%d %llx\n", len, val);
//printf("%16.16llx\n", v);
size_t start_pos = rand()%bits_per_slot;
assert(count_0s_gcc(v, start_pos) ==
count_0s_other(v, start_pos));
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment