Skip to content

Instantly share code, notes, and snippets.

@szastupov
Created March 2, 2010 21:32
Show Gist options
  • Save szastupov/319974 to your computer and use it in GitHub Desktop.
Save szastupov/319974 to your computer and use it in GitHub Desktop.
template <class T>
int ffs(T i)
{
T step = sizeof(i)*8 >> 1;
int n = 1;
for (; step > 1; step >>= 1) {
T shift = ((T)1 << step)-1;
if (!(i & shift)) {
n += step;
i >>= step;
}
}
return i ? (n + ((i+1) & 1)) : 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment