Skip to content

Instantly share code, notes, and snippets.

@jnthn
Forked from bdw/ffs.c
Created March 8, 2017 12:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jnthn/bdaf6aa21216a99fe153dd5e2555fee7 to your computer and use it in GitHub Desktop.
Save jnthn/bdaf6aa21216a99fe153dd5e2555fee7 to your computer and use it in GitHub Desktop.
cross-platform first set bit
#include <stdio.h>
#include <stdlib.h>
#define MVMint32 int
#ifdef __GNUC__
#define FFS(x) __builtin_ffs(x)
#elif defined(_MSC_VER)
static __inline MVMint32 FFS(MVMint32 x) {
MVMint32 i = 0;
if (_BitScanForward(&i, x) == 0)
return 0;
return i + 1;
}
#else
#error "Can't define Find First Set"
#endif
int main (int argc, char **argv) {
int v, f;
if (argc < 2)
return 0;
v = atoi(argv[1]);
f = FFS(v);
fprintf(stderr, "%d %d\n", v, f);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment