Last active
March 4, 2022 18:44
-
-
Save theoknock/b28e2de6c9a8e80f711ee9c06003152d to your computer and use it in GitHub Desktop.
Get the integer position of the set bit in a bit vector (field)
This file contains hidden or 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
// Example: | |
// 000100 (the value of bit vector x) returns 16 (use (x << 4) & 1UL to verify) | |
// To find the position of the set bit that returned 16, | |
// use floor(log2(16)) to get 4. | |
// Creates bit vector j and sets the ith bit out of 5… | |
// …returns the value of bit vector j, which is i raised to the power of two (2, 4, 8, 16, 32)… | |
// …returns the position of the set bit in bit vector j, which should coincide with i | |
// | |
for (int i = 1; i < 5; i++) { | |
unsigned int j = (1UL << i); | |
int position = floor(log2(j)); | |
printf("position of j (%d) == %d\t(%d)\n", j, position, i); | |
} | |
// Other solutions use a recursive function (or block) to iterate each bit in the vector, | |
// counting the number of 0s before returning the sum at the first set bit: | |
// | |
long (^Log2n_recursive)(unsigned int) = ^ long (unsigned int property) { | |
return (property > 1) ? 1 + Log2n_recursive(property / 2) : 0; | |
// return floor(log2(property)); // replace the line above with this more efficient, unconditional, non-recursive and nonbranching algorithm | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment