Skip to content

Instantly share code, notes, and snippets.

@winex
Created October 13, 2011 03:04
Show Gist options
  • Save winex/1283243 to your computer and use it in GitHub Desktop.
Save winex/1283243 to your computer and use it in GitHub Desktop.
bits set counting and iteration
#include <stdint.h>
#include <stdio.h>
int main(int argc, char* argv[])
{
uint32_t value = 0x8421;
uint32_t out = 0;
uint32_t bits = 0;
for (bits = value, out = 0; bits; bits &= (bits - 1), out++)
printf("bits: 0x%08x count: %02d\n", bits, out);
bits = value;
do
{
out = bits;
bits &= bits - 1;
out &= ~bits;
printf("bits: 0x%08x out: 0x%08x %d\n", bits, out, out);
} while (bits);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment