Created
November 27, 2010 15:43
-
-
Save neesenk/717992 to your computer and use it in GitHub Desktop.
fast ffs and ffsl
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
static char ffslut32[] = { | |
32, 1, 23, 2, 29, 24, 14, 3, 30, 27, 25, 18, 20, 15, 10, 4, | |
31, 22, 28, 13, 26, 17, 19, 9, 21, 12, 16, 8, 11, 7, 6, 5 | |
}; | |
static char ffslut64[] = { | |
64, 1, 48, 2, 57, 49, 28, 3, 61, 58, 50, 42, 38, 29, 17, 4, | |
62, 55, 59, 36, 53, 51, 43, 22, 45, 39, 33, 30, 24, 18, 12, 5, | |
63, 47, 56, 27, 60, 41, 37, 16, 54, 35, 52, 21, 44, 32, 23, 11, | |
46, 26, 40, 15, 34, 20, 31, 10, 25, 14, 19, 9, 13, 8, 7, 6 | |
}; | |
static int ffs32(uint32_t mask) | |
{ | |
return mask ? ffslut32[((mask & (-mask)) * 0x0FB9AC52) >> 27] : 0; | |
} | |
static int ffs64(uint64_t mask) | |
{ | |
return mask ? ffslut64[((mask & (-mask)) * 0x07EF3AE369961512ULL) >> 58] : 0; | |
} | |
int ffs(int mask) | |
{ | |
if (sizeof(int) == 8) | |
return ffs64(mask); | |
if (sizeof(int) == 4) | |
return ffs32(mask); | |
return -1; | |
} | |
int ffsl(long mask) | |
{ | |
if (sizeof(long) == 8) | |
return ffs64(mask); | |
if (sizeof(long) == 4) | |
return ffs32(mask); | |
return -1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment