Skip to content

Instantly share code, notes, and snippets.

@kaityo256
Created October 8, 2017 08:15
Show Gist options
  • Save kaityo256/2e153deb8d9b0dffb01c0dc1ed6d91d9 to your computer and use it in GitHub Desktop.
Save kaityo256/2e153deb8d9b0dffb01c0dc1ed6d91d9 to your computer and use it in GitHub Desktop.
Find the left-most bit
#include <cstdio>
#include <cstdint>
#include <cstdlib>
void
show_bit(uint32_t v) {
for (int i = 0; i < 32; i++) {
printf("%d", (v & (1ll << (31 - i)) ? 1 : 0));
}
printf("\n");
}
uint32_t
lmb(uint32_t v) {
if (v == 0)return 0;
else {
return 1 << (31 ^ __builtin_clz(v));
}
}
int
main(void) {
for (uint32_t i = 0; i < 5; i++) {
int v = rand();
printf("\n");
show_bit(v);
show_bit(lmb(v));
}
}
@kaityo256
Copy link
Author

$ ./a.out
00000000000000000100000110100111
00000000000000000100000000000000

00010000110101100011101011110001
00010000000000000000000000000000

01100000101101111010110011011001
01000000000000000000000000000000

00111010101101010000110000101010
00100000000000000000000000000000

01000100001100011011011110000010
01000000000000000000000000000000

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment