Skip to content

Instantly share code, notes, and snippets.

@javascripter
Created August 28, 2010 02:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save javascripter/554607 to your computer and use it in GitHub Desktop.
Save javascripter/554607 to your computer and use it in GitHub Desktop.
#include <stdio.h>
/* http://d.hatena.ne.jp/Cherenkov/20100827/p1 のビット演算的解法 */
typedef unsigned char uchar;
void putbits(uchar n) { /* 二進表現で出力 */
uchar i;
for (i = 128; i; i >>= 1) {
putchar(n & i ? '1' : '0');
}
putchar('\n');
}
uchar pop(uchar n) { /* 1のビットを数える */
uchar i;
for (i = 0; n; i++) {
n &= n - 1;
}
return i;
}
int main(void) {
uchar n = 86; /* 01010110 */
/* 全ビットが1の状態からnの0のビットぶん左にシフトする */
putbits(~0 << pop(~n));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment