Skip to content

Instantly share code, notes, and snippets.

@robertvunabandi
Created October 31, 2019 04:25
Show Gist options
  • Save robertvunabandi/2d90295684ddbfb7e3a7f6b4e209f4a8 to your computer and use it in GitHub Desktop.
Save robertvunabandi/2d90295684ddbfb7e3a7f6b4e209f4a8 to your computer and use it in GitHub Desktop.
int most_significant_bit_position(size_t value) {
// int count = 0;
// while (value != 0) {
// value >>= 1;
// count++;
// }
// return count;
assert(value > 0);
value = (uint64_t) value;
int count = 0;
printf("----\n");
printf("value: %zx, count: %d\n", value, count);
if ((value & 0x00000000FFFFFFFF) == 0) {
count += 32;
value = value >> 32;
}
if ((value & 0x000000000000FFFF) == 0) {
count += 16;
value = value >> 16;
}
if ((value & 0x00000000000000FF) == 0) {
count += 8;
value = value >> 8;
}
if ((value & 0x000000000000000F) == 0) {
count += 4;
value = value >> 4;
}
if ((value & 0x0000000000000003) == 0) {
count += 2;
value = value >> 2;
}
if ((value & 0x0000000000000001) == 0) {
count += 1;
}
printf("value: %zx, count: %d\n", value, count);
printf("returning: 64-count: %d\n", 64-count);
return 64 - count;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment